prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>font_icon.rs<|end_file_name|><|fim▁begin|>use crate::{
proc_macros::IntoRenderObject,
render_object::*,
utils::{Brush, Point, Rectangle},
};
/// The `FontIconRenderObject` holds the font icons inside
/// a render object.
#[derive(Debug, IntoRenderObject)]
pub struct FontIconRenderObject;
impl RenderObject for FontIconRenderObject {
fn render_self(&self, ctx: &mut Context, global_position: &Point) {
let (bounds, icon, icon_brush, icon_font, icon_size) = {
let widget = ctx.widget();
(
*widget.get::<Rectangle>("bounds"),
widget.clone::<String>("icon"),
widget.get::<Brush>("icon_brush").clone(),
widget.get::<String>("icon_font").clone(),
*widget.get::<f64>("icon_size"),
)
};
if bounds.width() == 0.0
|| bounds.height() == 0.0
|| icon_brush.is_transparent()
|| icon_size == 0.0
|| icon.is_empty()
{
return;
}
if !icon.is_empty() {
ctx.render_context_2_d().begin_path();
ctx.render_context_2_d().set_font_family(icon_font);<|fim▁hole|> ctx.render_context_2_d().set_font_size(icon_size);
ctx.render_context_2_d().set_fill_style(icon_brush);
ctx.render_context_2_d().fill_text(
&icon,
global_position.x() + bounds.x(),
global_position.y() + bounds.y(),
);
ctx.render_context_2_d().close_path();
}
}
}<|fim▁end|> | |
<|file_name|>display_top_prons.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__author__ = "Marelie Davel"
__email__ = "[email protected]"
"""
Display the dictionary pronunciations of the most frequent words occuring in a speech corpus
@param in_trans_list: List of transcription filenames
@param in_dict: Pronunciation dictionary
@param top_n: Number of words to verify
@param out_name: Name of output file for results
"""
import sys, operator, codecs
#------------------------------------------------------------------------------
def display_top_prons(trans_list_name, dict_name, top_n, out_name):
"""Display the dictionary pronunciations of the most frequent words occuring in a speech corpus"""
#Read dictionary
pron_dict = {}
try:
dict_file = codecs.open(dict_name,"r","utf8")
except IOError:
print "Error: Error reading from file " + dict_name
sys.exit(1)
for ln in dict_file:
ln = ln.strip()
parts = ln.split("\t")
if len(parts) != 2:
print "Error: dictionary format error line %s" % ln
word = parts[0]
pron = parts[1]
if pron_dict.has_key(word):
pron_dict[word].append(pron)
else:
pron_dict[word] = []
pron_dict[word].append(pron)
dict_file.close()
#Read and cnt words in transcriptions
counts = {}
try:
list_file = codecs.open(trans_list_name,"r","utf8")
except IOError:
print "Error: Error reading from file " + trans_list_name
sys.exit(1)
for trans_name in list_file:
trans_name = trans_name.strip()
try:
trans_file = codecs.open(trans_name,"r","utf8")
except IOError:
print "Error: Error reading from file " + trans_name
sys.exit(1)
for ln in trans_file:
ln = ln.strip()
parts = ln.split(" ")
for word in parts:
if counts.has_key(word):
counts[word] = counts[word]+1
else:
counts[word] = 1
trans_file.close()
list_file.close()
#Now write top pronunciations to file
try:
out_file = codecs.open(out_name,"w","utf8")
except IOError:
print "Error: Error writing to file " + out_name
sys.exit(1)
top_words = sorted(counts.items(),key=operator.itemgetter(1),reverse=True)
n = 0;
for (w,c) in top_words:
if n < top_n:
if pron_dict.has_key(w):
for var_pron in pron_dict[w]:
out_file.write("%d\t%-20s\t%s\n" % (c,w,var_pron) )
n = n+1
else:
print "Error: unknown word %s" % word
else:
break
out_file.close()
#------------------------------------------------------------------------------
if __name__ == "__main__":
if len(sys.argv) == 5:
trans_list_name = str(sys.argv[1])
dict_name = str(sys.argv[2])
top_n = int(sys.argv[3])
out_name = str(sys.argv[4])
print "Displaying the %d most frequent words" % top_n
display_top_prons(trans_list_name, dict_name, top_n, out_name)
else:
print "\nDisplay the dictionary pronunciations of the most frequent words in a speech corpus."
print "Usage: display_top_prons.py <in:trans_list> <in:dict> <n> <out:results>"
print " <in:trans_list> list of transcription filenames"
print " <in:dict> pronunciation dictionary"
print " <n> number of words to verify"
print " <out:results> name of output file for results"
#------------------------------------------------------------------------------<|fim▁end|> | #
# Copyright 2013 CSIR Meraka HLT and Multilingual Speech Technologies (MuST) North-West University
# |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>const fs = require('fs');
const dns = require('dns');
const argv = require('yargs').argv;
const Seismometer = require('./seismometer');
const Communicator = require('./communicator');
function assertOnline() {
return new Promise((fulfill, reject) => {
dns.resolve('www.google.com', err => {
if (err) {
reject(new Error('Not online. Cannot resolve www.google.com'));
} else {
fulfill();
}
});
});
}
function main() {
if (argv.help) {
console.log('usage: npm run [--port /dev/port]');
process.exit(0);
}
if (argv.port) {
if (!fs.existsSync(argv.port)) {
console.error(`Port "${argv.port}" does not exist.`);
process.exit(1);
}
}
const communicator = new Communicator();
const seismometer = new Seismometer();
seismometer.watch();
assertOnline()
.then(() => communicator.connect(argv.port))
.then(() => {
console.log('Connected to', communicator.port.path);
seismometer.on('quake', info => {
console.log(`Quake! At ${info.date} with a magnitude of ${info.magnitude}`);
communicator.send(info);
});
console.log('Watching for quakes...');
})
.catch(err => {<|fim▁hole|> console.error(err);
process.exit(1);
});
}
main();<|fim▁end|> | |
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################<|fim▁hole|># OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': ' Customer points based on invoice amounts',
'version': '1.0',
'category': 'Generic Modules',
'author': 'Rajkumar',
'website': 'http://www.openerp.com',
'depends': ['product','base','account'],
'init_xml': [ ],
'update_xml': ['customer_commission.xml','customer_commission_board_view.xml'],
'demo_xml': [ ],
'test': [ ],
'installable': True,
'active': False,
'description': """ Customer points are created as based on invoice amounts
using these points to reduce the invoice amount another payments"""
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|> | # |
<|file_name|>OpennmsKafkaProducer.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2018-2020 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2020 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.features.kafka.producer;
import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.opennms.core.ipc.common.kafka.Utils;
import org.opennms.features.kafka.producer.datasync.KafkaAlarmDataSync;
import org.opennms.features.kafka.producer.model.OpennmsModelProtos;
import org.opennms.features.situationfeedback.api.AlarmFeedback;
import org.opennms.features.situationfeedback.api.AlarmFeedbackListener;
import org.opennms.netmgt.alarmd.api.AlarmCallbackStateTracker;
import org.opennms.netmgt.alarmd.api.AlarmLifecycleListener;
import org.opennms.netmgt.events.api.EventListener;
import org.opennms.netmgt.events.api.EventSubscriptionService;
import org.opennms.netmgt.events.api.ThreadAwareEventListener;
import org.opennms.netmgt.events.api.model.IEvent;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyConsumer;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyDao;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyEdge;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyMessage;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyMessage.TopologyMessageStatus;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyProtocol;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyVertex;
import org.opennms.netmgt.topologies.service.api.TopologyVisitor;
import org.opennms.netmgt.xml.event.Event;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.swrve.ratelimitedlogger.RateLimitedLog;
public class OpennmsKafkaProducer implements AlarmLifecycleListener, EventListener, AlarmFeedbackListener, OnmsTopologyConsumer, ThreadAwareEventListener {
private static final Logger LOG = LoggerFactory.getLogger(OpennmsKafkaProducer.class);
private static final RateLimitedLog RATE_LIMITED_LOGGER = RateLimitedLog
.withRateLimit(LOG)
.maxRate(5).every(Duration.ofSeconds(30))
.build();
public static final String KAFKA_CLIENT_PID = "org.opennms.features.kafka.producer.client";
private static final ExpressionParser SPEL_PARSER = new SpelExpressionParser();
private final ThreadFactory nodeUpdateThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("kafka-producer-node-update-%d")
.build();
private final ProtobufMapper protobufMapper;
private final NodeCache nodeCache;
private final ConfigurationAdmin configAdmin;
private final EventSubscriptionService eventSubscriptionService;
private KafkaAlarmDataSync dataSync;
private String eventTopic;
private String alarmTopic;
private String nodeTopic;
private String alarmFeedbackTopic;
private String topologyVertexTopic;
private String topologyEdgeTopic;
private boolean forwardEvents;
private boolean forwardAlarms;
private boolean forwardAlarmFeedback;
private boolean suppressIncrementalAlarms;
private boolean forwardNodes;
private Expression eventFilterExpression;
private Expression alarmFilterExpression;
private final CountDownLatch forwardedEvent = new CountDownLatch(1);
private final CountDownLatch forwardedAlarm = new CountDownLatch(1);
private final CountDownLatch forwardedNode = new CountDownLatch(1);
private final CountDownLatch forwardedAlarmFeedback = new CountDownLatch(1);
private final CountDownLatch forwardedTopologyVertexMessage = new CountDownLatch(1);
private final CountDownLatch forwardedTopologyEdgeMessage = new CountDownLatch(1);
private KafkaProducer<byte[], byte[]> producer;
private final Map<String, OpennmsModelProtos.Alarm> outstandingAlarms = new ConcurrentHashMap<>();
private final AlarmEqualityChecker alarmEqualityChecker =
AlarmEqualityChecker.with(AlarmEqualityChecker.Exclusions::defaultExclusions);
private final AlarmCallbackStateTracker stateTracker = new AlarmCallbackStateTracker();
private final OnmsTopologyDao topologyDao;
private int kafkaSendQueueCapacity;
private BlockingDeque<KafkaRecord> kafkaSendDeque;
private final ExecutorService kafkaSendQueueExecutor =
Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "KafkaSendQueueProcessor"));
private final ExecutorService nodeUpdateExecutor;
private String encoding = "UTF8";
private int numEventListenerThreads = 4;
public OpennmsKafkaProducer(ProtobufMapper protobufMapper, NodeCache nodeCache,
ConfigurationAdmin configAdmin, EventSubscriptionService eventSubscriptionService,
OnmsTopologyDao topologyDao, int nodeAsyncUpdateThreads) {
this.protobufMapper = Objects.requireNonNull(protobufMapper);
this.nodeCache = Objects.requireNonNull(nodeCache);
this.configAdmin = Objects.requireNonNull(configAdmin);
this.eventSubscriptionService = Objects.requireNonNull(eventSubscriptionService);
this.topologyDao = Objects.requireNonNull(topologyDao);
this.nodeUpdateExecutor = Executors.newFixedThreadPool(nodeAsyncUpdateThreads, nodeUpdateThreadFactory);
}
public void init() throws IOException {
// Create the Kafka producer
final Properties producerConfig = new Properties();
final Dictionary<String, Object> properties = configAdmin.getConfiguration(KAFKA_CLIENT_PID).getProperties();
if (properties != null) {
final Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
final String key = keys.nextElement();
producerConfig.put(key, properties.get(key));
}
}
// Overwrite the serializers, since we rely on these
producerConfig.put("key.serializer", ByteArraySerializer.class.getCanonicalName());
producerConfig.put("value.serializer", ByteArraySerializer.class.getCanonicalName());
// Class-loader hack for accessing the kafka classes when initializing producer.
producer = Utils.runWithGivenClassLoader(() -> new KafkaProducer<>(producerConfig), KafkaProducer.class.getClassLoader());
// Start processing records that have been queued for sending
if (kafkaSendQueueCapacity <= 0) {
kafkaSendQueueCapacity = 1000;
LOG.info("Defaulted the 'kafkaSendQueueCapacity' to 1000 since no property was set");
}
kafkaSendDeque = new LinkedBlockingDeque<>(kafkaSendQueueCapacity);
kafkaSendQueueExecutor.execute(this::processKafkaSendQueue);
if (forwardEvents) {
eventSubscriptionService.addEventListener(this);
}
topologyDao.subscribe(this);
}
public void destroy() {
kafkaSendQueueExecutor.shutdownNow();
nodeUpdateExecutor.shutdownNow();
if (producer != null) {
producer.close();
producer = null;
}
if (forwardEvents) {
eventSubscriptionService.removeEventListener(this);
}
topologyDao.unsubscribe(this);
}
private void forwardTopologyMessage(OnmsTopologyMessage message) {
if (message.getProtocol() == null) {
LOG.error("forwardTopologyMessage: null protocol");
return;
}
if (message.getMessagestatus() == null) {
LOG.error("forwardTopologyMessage: null status");
return;
}
if (message.getMessagebody() == null) {
LOG.error("forwardTopologyMessage: null message");
return;
}
if (message.getMessagestatus() == TopologyMessageStatus.DELETE) {
message.getMessagebody().accept(new DeletingVisitor(message));
} else {
message.getMessagebody().accept(new UpdatingVisitor(message));
}
}
private void forwardTopologyEdgeMessage(byte[] refid, byte[] message) {
sendRecord(() -> {
return new ProducerRecord<>(topologyEdgeTopic, refid, message);
}, recordMetadata -> {
// We've got an ACK from the server that the event was forwarded
// Let other threads know when we've successfully forwarded an event
forwardedTopologyEdgeMessage.countDown();
});
}
private void forwardEvent(Event event) {
boolean shouldForwardEvent = true;
// Filtering
if (eventFilterExpression != null) {
try {
shouldForwardEvent = eventFilterExpression.getValue(event, Boolean.class);
} catch (Exception e) {
LOG.error("Event filter '{}' failed to return a result for event: {}. The event will be forwarded anyways.",
eventFilterExpression.getExpressionString(), event.toStringSimple(), e);
}
}
if (!shouldForwardEvent) {
if (LOG.isTraceEnabled()) {
LOG.trace("Event {} not forwarded due to event filter: {}",
event.toStringSimple(), eventFilterExpression.getExpressionString());
}
return;
}
// Node handling
if (forwardNodes && event.getNodeid() != null && event.getNodeid() != 0) {
updateNodeAsynchronously(event.getNodeid());
}
// Forward!
sendRecord(() -> {
final OpennmsModelProtos.Event mappedEvent = protobufMapper.toEvent(event).build();
LOG.debug("Sending event with UEI: {}", mappedEvent.getUei());
return new ProducerRecord<>(eventTopic, mappedEvent.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the event was forwarded
// Let other threads know when we've successfully forwarded an event
forwardedEvent.countDown();
});
}
public boolean shouldForwardAlarm(OnmsAlarm alarm) {
if (alarmFilterExpression != null) {
// The expression is not necessarily thread safe
synchronized (this) {
try {
final boolean shouldForwardAlarm = alarmFilterExpression.getValue(alarm, Boolean.class);
if (LOG.isTraceEnabled()) {
LOG.trace("Alarm {} not forwarded due to event filter: {}",
alarm, alarmFilterExpression.getExpressionString());
}
return shouldForwardAlarm;
} catch (Exception e) {
LOG.error("Alarm filter '{}' failed to return a result for event: {}. The alarm will be forwarded anyways.",
alarmFilterExpression.getExpressionString(), alarm, e);
}
}
}
return true;
}
private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) {
OpennmsModelProtos.Alarm existingAlarm = outstandingAlarms.get(reductionKey);
return existingAlarm != null && alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm),
existingAlarm);
}
private void recordIncrementalAlarm(String reductionKey, OnmsAlarm alarm) {
// Apply the excluded fields when putting to the map so we do not have to perform this calculation
// on each equality check
outstandingAlarms.put(reductionKey,
AlarmEqualityChecker.Exclusions.defaultExclusions(protobufMapper.toAlarm(alarm)).build());
}
private void updateAlarm(String reductionKey, OnmsAlarm alarm) {
// Always push null records, no good way to perform filtering on these
if (alarm == null) {
// The alarm has been deleted so we shouldn't track it in the map of outstanding alarms any longer
outstandingAlarms.remove(reductionKey);
// The alarm was deleted, push a null record to the reduction key
sendRecord(() -> {
LOG.debug("Deleting alarm with reduction key: {}", reductionKey);
return new ProducerRecord<>(alarmTopic, reductionKey.getBytes(encoding), null);
}, recordMetadata -> {
// We've got an ACK from the server that the alarm was forwarded
// Let other threads know when we've successfully forwarded an alarm
forwardedAlarm.countDown();
});
return;
}
// Filtering
if (!shouldForwardAlarm(alarm)) {
return;
}
if (suppressIncrementalAlarms && isIncrementalAlarm(reductionKey, alarm)) {
return;
}
// Node handling
if (forwardNodes && alarm.getNodeId() != null) {
updateNodeAsynchronously(alarm.getNodeId());
}
// Forward!
sendRecord(() -> {
final OpennmsModelProtos.Alarm mappedAlarm = protobufMapper.toAlarm(alarm).build();
LOG.debug("Sending alarm with reduction key: {}", reductionKey);
if (suppressIncrementalAlarms) {
recordIncrementalAlarm(reductionKey, alarm);
}
return new ProducerRecord<>(alarmTopic, reductionKey.getBytes(encoding), mappedAlarm.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the alarm was forwarded
// Let other threads know when we've successfully forwarded an alarm
forwardedAlarm.countDown();
});
}
private void updateNodeAsynchronously(long nodeId) {
// Updating node asynchronously will unblock event consumption.
nodeUpdateExecutor.execute(() -> {
maybeUpdateNode(nodeId);
});
}
private void maybeUpdateNode(long nodeId) {
nodeCache.triggerIfNeeded(nodeId, (node) -> {
final String nodeCriteria;
if (node != null && node.getForeignSource() != null && node.getForeignId() != null) {
nodeCriteria = String.format("%s:%s", node.getForeignSource(), node.getForeignId());
} else {
nodeCriteria = Long.toString(nodeId);
}
if (node == null) {
// The node was deleted, push a null record
sendRecord(() -> {
LOG.debug("Deleting node with criteria: {}", nodeCriteria);
return new ProducerRecord<>(nodeTopic, nodeCriteria.getBytes(encoding), null);
});
return;
}
sendRecord(() -> {
final OpennmsModelProtos.Node mappedNode = protobufMapper.toNode(node).build();
LOG.debug("Sending node with criteria: {}", nodeCriteria);
return new ProducerRecord<>(nodeTopic, nodeCriteria.getBytes(encoding), mappedNode.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the node was forwarded
// Let other threads know when we've successfully forwarded a node
forwardedNode.countDown();
});
});
}
private void sendRecord(Callable<ProducerRecord<byte[], byte[]>> callable) {
sendRecord(callable, null);
}
private void sendRecord(Callable<ProducerRecord<byte[], byte[]>> callable, Consumer<RecordMetadata> callback) {
if (producer == null) {
return;
}
final ProducerRecord<byte[], byte[]> record;
try {
record = callable.call();
} catch (Exception e) {
// Propagate
throw new RuntimeException(e);
}
// Rather than attempt to send, we instead queue the record to avoid blocking since KafkaProducer's send()
// method can block if Kafka is not available when metadata is attempted to be retrieved
// Any offer that fails due to capacity overflow will simply be dropped and will have to wait until the next
// sync to be processed so this is just a best effort attempt
if (!kafkaSendDeque.offer(new KafkaRecord(record, callback))) {
RATE_LIMITED_LOGGER.warn("Dropped a Kafka record due to queue capacity being full.");
}
}
private void processKafkaSendQueue() {
//noinspection InfiniteLoopStatement
while (true) {
try {
KafkaRecord kafkaRecord = kafkaSendDeque.take();
ProducerRecord<byte[], byte[]> producerRecord = kafkaRecord.getProducerRecord();
Consumer<RecordMetadata> consumer = kafkaRecord.getConsumer();
try {
producer.send(producerRecord, (recordMetadata, e) -> {
if (e != null) {
LOG.warn("Failed to send record to producer: {}.", producerRecord, e);
if (e instanceof TimeoutException) {
// If Kafka is Offline, buffer the record again for events.
// This is best effort to keep the order although in-flight elements may still miss the order.
if (producerRecord != null &&
this.eventTopic.equalsIgnoreCase(producerRecord.topic())) {
if(!kafkaSendDeque.offerFirst(kafkaRecord)) {
RATE_LIMITED_LOGGER.warn("Dropped a Kafka record due to queue capacity being full.");
}
}
}
return;
}
if (consumer != null) {
consumer.accept(recordMetadata);
}
});
} catch (RuntimeException e) {
LOG.warn("Failed to send record to producer: {}.", producerRecord, e);
}
} catch (InterruptedException ignore) {
break;
}
}
}
@Override
public void handleAlarmSnapshot(List<OnmsAlarm> alarms) {
if (!forwardAlarms || dataSync == null) {
// Ignore<|fim▁hole|>
@Override
public void preHandleAlarmSnapshot() {
stateTracker.startTrackingAlarms();
}
@Override
public void postHandleAlarmSnapshot() {
stateTracker.resetStateAndStopTrackingAlarms();
}
@Override
public void handleNewOrUpdatedAlarm(OnmsAlarm alarm) {
if (!forwardAlarms) {
// Ignore
return;
}
updateAlarm(alarm.getReductionKey(), alarm);
stateTracker.trackNewOrUpdatedAlarm(alarm.getId(), alarm.getReductionKey());
}
@Override
public void handleDeletedAlarm(int alarmId, String reductionKey) {
if (!forwardAlarms) {
// Ignore
return;
}
handleDeletedAlarm(reductionKey);
stateTracker.trackDeletedAlarm(alarmId, reductionKey);
}
private void handleDeletedAlarm(String reductionKey) {
updateAlarm(reductionKey, null);
}
@Override
public String getName() {
return OpennmsKafkaProducer.class.getName();
}
@Override
public void onEvent(IEvent event) {
forwardEvent(Event.copyFrom(event));
}
@Override
public Set<OnmsTopologyProtocol> getProtocols() {
return Collections.singleton(OnmsTopologyProtocol.allProtocols());
}
@Override
public void consume(OnmsTopologyMessage message) {
forwardTopologyMessage(message);
}
public void setTopologyVertexTopic(String topologyVertexTopic) {
this.topologyVertexTopic = topologyVertexTopic;
}
public void setTopologyEdgeTopic(String topologyEdgeTopic) {
this.topologyEdgeTopic = topologyEdgeTopic;
}
public void setEventTopic(String eventTopic) {
this.eventTopic = eventTopic;
forwardEvents = !Strings.isNullOrEmpty(eventTopic);
}
public void setAlarmTopic(String alarmTopic) {
this.alarmTopic = alarmTopic;
forwardAlarms = !Strings.isNullOrEmpty(alarmTopic);
}
public void setNodeTopic(String nodeTopic) {
this.nodeTopic = nodeTopic;
forwardNodes = !Strings.isNullOrEmpty(nodeTopic);
}
public void setAlarmFeedbackTopic(String alarmFeedbackTopic) {
this.alarmFeedbackTopic = alarmFeedbackTopic;
forwardAlarmFeedback = !Strings.isNullOrEmpty(alarmFeedbackTopic);
}
public void setEventFilter(String eventFilter) {
if (Strings.isNullOrEmpty(eventFilter)) {
eventFilterExpression = null;
} else {
eventFilterExpression = SPEL_PARSER.parseExpression(eventFilter);
}
}
public void setAlarmFilter(String alarmFilter) {
if (Strings.isNullOrEmpty(alarmFilter)) {
alarmFilterExpression = null;
} else {
alarmFilterExpression = SPEL_PARSER.parseExpression(alarmFilter);
}
}
public OpennmsKafkaProducer setDataSync(KafkaAlarmDataSync dataSync) {
this.dataSync = dataSync;
return this;
}
@Override
public void handleAlarmFeedback(List<AlarmFeedback> alarmFeedback) {
if (!forwardAlarmFeedback) {
return;
}
// NOTE: This will currently block while waiting for Kafka metadata if Kafka is not available.
alarmFeedback.forEach(feedback -> sendRecord(() -> {
LOG.debug("Sending alarm feedback with key: {}", feedback.getAlarmKey());
return new ProducerRecord<>(alarmFeedbackTopic, feedback.getAlarmKey().getBytes(encoding),
protobufMapper.toAlarmFeedback(feedback).build().toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the alarm feedback was forwarded
// Let other threads know when we've successfully forwarded an alarm feedback
forwardedAlarmFeedback.countDown();
}));
}
public boolean isForwardingAlarms() {
return forwardAlarms;
}
public CountDownLatch getEventForwardedLatch() {
return forwardedEvent;
}
public CountDownLatch getAlarmForwardedLatch() {
return forwardedAlarm;
}
public CountDownLatch getNodeForwardedLatch() {
return forwardedNode;
}
public CountDownLatch getAlarmFeedbackForwardedLatch() {
return forwardedAlarmFeedback;
}
public void setSuppressIncrementalAlarms(boolean suppressIncrementalAlarms) {
this.suppressIncrementalAlarms = suppressIncrementalAlarms;
}
@VisibleForTesting
KafkaAlarmDataSync getDataSync() {
return dataSync;
}
public AlarmCallbackStateTracker getAlarmCallbackStateTracker() {
return stateTracker;
}
public void setKafkaSendQueueCapacity(int kafkaSendQueueCapacity) {
this.kafkaSendQueueCapacity = kafkaSendQueueCapacity;
}
@Override
public int getNumThreads() {
return numEventListenerThreads;
}
private static final class KafkaRecord {
private final ProducerRecord<byte[], byte[]> producerRecord;
private final Consumer<RecordMetadata> consumer;
KafkaRecord(ProducerRecord<byte[], byte[]> producerRecord, Consumer<RecordMetadata> consumer) {
this.producerRecord = producerRecord;
this.consumer = consumer;
}
ProducerRecord<byte[], byte[]> getProducerRecord() {
return producerRecord;
}
Consumer<RecordMetadata> getConsumer() {
return consumer;
}
}
public CountDownLatch getForwardedTopologyVertexMessage() {
return forwardedTopologyVertexMessage;
}
public CountDownLatch getForwardedTopologyEdgeMessage() {
return forwardedTopologyEdgeMessage;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public int getNumEventListenerThreads() {
return numEventListenerThreads;
}
public void setNumEventListenerThreads(int numEventListenerThreads) {
this.numEventListenerThreads = numEventListenerThreads;
}
private class TopologyVisitorImpl implements TopologyVisitor {
final OnmsTopologyMessage onmsTopologyMessage;
TopologyVisitorImpl(OnmsTopologyMessage onmsTopologyMessage) {
this.onmsTopologyMessage = Objects.requireNonNull(onmsTopologyMessage);
}
byte[] getKeyForEdge(OnmsTopologyEdge edge) {
Objects.requireNonNull(onmsTopologyMessage);
return String.format("topology:%s:%s", onmsTopologyMessage.getProtocol().getId(), edge.getId()).getBytes();
}
}
private class DeletingVisitor extends TopologyVisitorImpl {
DeletingVisitor(OnmsTopologyMessage topologyMessage) {
super(topologyMessage);
}
@Override
public void visit(OnmsTopologyEdge edge) {
forwardTopologyEdgeMessage(getKeyForEdge(edge), null);
}
}
private class UpdatingVisitor extends TopologyVisitorImpl {
UpdatingVisitor(OnmsTopologyMessage onmsTopologyMessage) {
super(onmsTopologyMessage);
}
@Override
public void visit(OnmsTopologyVertex vertex) {
// Node handling
if (forwardNodes && vertex.getNodeid() != null) {
updateNodeAsynchronously(vertex.getNodeid());
}
}
@Override
public void visit(OnmsTopologyEdge edge) {
Objects.requireNonNull(onmsTopologyMessage);
final OpennmsModelProtos.TopologyEdge mappedTopoMsg =
protobufMapper.toEdgeTopologyMessage(onmsTopologyMessage.getProtocol(), edge);
forwardTopologyEdgeMessage(getKeyForEdge(edge), mappedTopoMsg.toByteArray());
}
}
}<|fim▁end|> | return;
}
dataSync.handleAlarmSnapshot(alarms);
} |
<|file_name|>get_state_events_for_empty_key.rs<|end_file_name|><|fim▁begin|>//! [GET /_matrix/client/r0/rooms/{roomId}/state/{eventType}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-state-eventtype)
use ruma_api::ruma_api;
use ruma_events::EventType;
use ruma_identifiers::RoomId;
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata {
description: "Get state events of a given type associated with the empty key.",
method: GET,
name: "get_state_events_for_empty_key",
path: "/_matrix/client/r0/rooms/:room_id/state/:event_type",
rate_limited: false,<|fim▁hole|> requires_authentication: true,
}
request {
/// The room to look up the state for.
#[ruma_api(path)]
pub room_id: RoomId,
/// The type of state to look up.
#[ruma_api(path)]
pub event_type: EventType,
}
response {
/// The content of the state event.
///
/// To create a `Box<RawJsonValue>`, use `serde_json::value::to_raw_value`.
#[ruma_api(body)]
pub content: Box<RawJsonValue>,
}
error: crate::Error
}<|fim▁end|> | |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | export * from './signup.component'; |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from distutils.core import setup
setup(
name='megad-mqtt-gw',
version='0.3',
description='Gateway between MQTT queue and MegaD devices (http://ab-log.ru)',
author='rs',
author_email='[email protected]',
url='https://github.com/repalov/megad-mqtt-gw',<|fim▁hole|> 'Environment :: Console',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: System :: Networking',
'License :: OSI Approved :: Apache Software License',
],
packages=['megad'],
install_requires=['aiohttp>=3.4.4', 'paho-mqtt>=1.4', 'netifaces>=0.10.7'],
data_files=[('/etc', ['megad-mqtt-gw.homeassistant.conf', 'megad-mqtt-gw.wirenboard.conf']),
('/lib/systemd/system', ['megad-mqtt-gw.service'])
],
entry_points={'console_scripts': ['megad-mqtt-gw=megad.megad_mqtt_gw:main']}
)<|fim▁end|> | license='Apache License',
classifiers=[
'Development Status :: 4 - Beta', |
<|file_name|>pherf-standalone.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
############################################################################
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
############################################################################
from __future__ import print_function
from phoenix_utils import tryDecode
import os
import subprocess
import sys
import phoenix_utils
phoenix_utils.setPath()
args = phoenix_utils.shell_quote(sys.argv[1:])
# HBase configuration folder path (where hbase-site.xml reside) for
# HBase/Phoenix client side property override
hbase_config_path = phoenix_utils.hbase_conf_dir
java_home = os.getenv('JAVA_HOME')
# load hbase-env.??? to extract JAVA_HOME, HBASE_PID_DIR, HBASE_LOG_DIR
hbase_env_path = None<|fim▁hole|> hbase_env_cmd = ['bash', '-c', 'source %s && env' % hbase_env_path]
elif os.name == 'nt':
hbase_env_path = os.path.join(hbase_config_path, 'hbase-env.cmd')
hbase_env_cmd = ['cmd.exe', '/c', 'call %s & set' % hbase_env_path]
if not hbase_env_path or not hbase_env_cmd:
sys.stderr.write("hbase-env file unknown on platform {}{}".format(os.name, os.linesep))
sys.exit(-1)
hbase_env = {}
if os.path.isfile(hbase_env_path):
p = subprocess.Popen(hbase_env_cmd, stdout = subprocess.PIPE)
for x in p.stdout:
(k, _, v) = tryDecode(x).partition('=')
hbase_env[k.strip()] = v.strip()
if 'JAVA_HOME' in hbase_env:
java_home = hbase_env['JAVA_HOME']
if java_home:
java = os.path.join(java_home, 'bin', 'java')
else:
java = 'java'
java_cmd = java +' -Xms512m -Xmx3072m -cp "' + \
phoenix_utils.pherf_conf_path + os.pathsep + \
phoenix_utils.hbase_conf_dir + os.pathsep + \
phoenix_utils.slf4j_backend_jar + os.pathsep + \
phoenix_utils.logging_jar + os.pathsep + \
phoenix_utils.phoenix_client_embedded_jar + os.pathsep +\
phoenix_utils.phoenix_pherf_jar + \
'" -Dlog4j.configuration=file:' + \
os.path.join(phoenix_utils.current_dir, "log4j.properties") + \
" org.apache.phoenix.pherf.Pherf " + args
os.execl("/bin/sh", "/bin/sh", "-c", java_cmd)<|fim▁end|> | hbase_env_cmd = None
if os.name == 'posix':
hbase_env_path = os.path.join(hbase_config_path, 'hbase-env.sh') |
<|file_name|>ActivityTests.py<|end_file_name|><|fim▁begin|>import base64
import json
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from ..views import register, statements, activities
class ActivityTests(TestCase):
@classmethod
def setUpClass(cls):
print "\n%s" % __name__
def setUp(self):
self.username = "tester"
self.email = "[email protected]"
self.password = "test"
self.auth = "Basic %s" % base64.b64encode("%s:%s" % (self.username, self.password))
form = {'username':self.username, 'email': self.email,'password':self.password,'password2':self.password}
self.client.post(reverse(register),form, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
def test_get(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType':'Activity', 'id':'act:foobar'}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId':'act:foobar'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar', rsp)
self.assertIn('Activity', rsp)
self.assertIn('objectType', rsp)
self.assertIn('content-length', response._headers)
def test_get_not_exist(self):
activity_id = "this:does_not_exist"
response = self.client.get(reverse(activities), {'activityId':activity_id}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content, 'No activity found with ID this:does_not_exist')
def test_get_not_array(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType':'Activity', 'id':'act:foobar'}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId':'act:foobar'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('content-length', response._headers)
rsp_obj = json.loads(rsp)
self.assertEqual('act:foobar', rsp_obj['id'])
def test_head(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType':'Activity', 'id':'act:foobar'}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.head(reverse(activities), {'activityId':'act:foobar'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, '')
self.assertIn('content-length', response._headers)
def test_get_def(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar1',
'definition': {'name': {'en-US':'testname', 'en-GB': 'altname'},
'description': {'en-US':'testdesc', 'en-GB': 'altdesc'},
'type': 'type:course','interactionType': 'other'}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId':'act:foobar1'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar1', rsp)
self.assertIn('type:course', rsp)
self.assertIn('other', rsp)
rsp_dict = json.loads(rsp)
self.assertEqual(len(rsp_dict['definition']['name'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['description'].keys()), 1)
def test_get_ext(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar2',
'definition': {'name': {'en-FR':'testname2'},'description': {'en-FR':'testdesc2'},
'type': 'type:course','interactionType': 'other',
'extensions': {'ext:key1': 'value1', 'ext:key2': 'value2'}}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId':'act:foobar2'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar2', rsp)
self.assertIn('type:course', rsp)
self.assertIn('other', rsp)
self.assertIn('en-FR', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('key1', rsp)
self.assertIn('key2', rsp)
self.assertIn('value1', rsp)
self.assertIn('value2', rsp)
def test_get_crp_multiple_choice(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar3',
'definition': {'name': {'en-FR':'testname2'},
'description': {'en-FR':'testdesc2', 'en-CH': 'altdesc'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'choice',
'correctResponsesPattern': ['golf', 'tetris'],'choices':[{'id': 'golf',
'description': {'en-US':'Golf Example', 'en-GB':'alt golf'}},{'id': 'tetris',
'description':{'en-US': 'Tetris Example'}}, {'id':'facebook',
'description':{'en-US':'Facebook App'}},{'id':'scrabble',
'description': {'en-US': 'Scrabble Example'}}]}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId':'act:foobar3'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar3', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('choice', rsp)
self.assertIn('en-FR', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('golf', rsp)
self.assertIn('tetris', rsp)
rsp_dict = json.loads(rsp)
self.assertEqual(len(rsp_dict['definition']['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['choices'][0]['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['choices'][1]['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['choices'][2]['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['choices'][3]['description'].keys()), 1)
def test_get_crp_true_false(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar4',
'definition': {'name': {'en-US':'testname2'},'description': {'en-US':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'true-false','correctResponsesPattern': ['true']}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar4'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar4', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('true-false', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('true', rsp)
def test_get_crp_fill_in(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar5',
'definition': {'name': {'en-US':'testname2'},'description': {'en-US':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'fill-in',
'correctResponsesPattern': ['Fill in answer']}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar5'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar5', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('fill-in', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('Fill in answer', rsp)
def test_get_crp_long_fill_in(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar6',
'definition': {'name': {'en-FR':'testname2'},'description': {'en-FR':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'fill-in',
'correctResponsesPattern': ['Long fill in answer']}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar6'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar6', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('fill-in', rsp)
self.assertIn('en-FR', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('Long fill in answer', rsp)
def test_get_crp_likert(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar7',
'definition': {'name': {'en-US':'testname2'},'description': {'en-US':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'likert','correctResponsesPattern': ['likert_3'],
'scale':[{'id': 'likert_0', 'description': {'en-US':'Its OK'}},{'id': 'likert_1',
'description':{'en-US': 'Its Pretty Cool'}}, {'id':'likert_2',
'description':{'en-US':'Its Cool Cool'}},{'id':'likert_3',
'description': {'en-US': 'Its Gonna Change the World'}}]}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar7'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar7', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('likert', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('likert_3', rsp)
self.assertIn('likert_2', rsp)
self.assertIn('likert_1', rsp)
def test_get_crp_matching(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar8',
'definition': {'name': {'en-US':'testname2'},'description': {'en-FR':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'matching',
'correctResponsesPattern': ['lou.3,tom.2,andy.1'],'source':[{'id': 'lou',
'description': {'en-US':'Lou'}},{'id': 'tom','description':{'en-US': 'Tom'}},
{'id':'andy', 'description':{'en-US':'Andy'}}],'target':[{'id':'1',
'description':{'en-US': 'SCORM Engine'}},{'id':'2','description':{'en-US': 'Pure-sewage'}},
{'id':'3', 'description':{'en-US': 'SCORM Cloud'}}]}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar8'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar8', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('matching', rsp)
self.assertIn('en-FR', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('lou.3,tom.2,andy.1', rsp)
self.assertIn('source', rsp)
self.assertIn('target', rsp)
def test_get_crp_performance(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar9',
'definition': {'name': {'en-US':'testname2', 'en-GB': 'altname'},
'description': {'en-US':'testdesc2'},'type': 'http://adlnet.gov/expapi/activities/cmi.interaction',
'interactionType': 'performance',
'correctResponsesPattern': ['pong.1,dg.10,lunch.4'],'steps':[{'id': 'pong',
'description': {'en-US':'Net pong matches won'}},{'id': 'dg',
'description':{'en-US': 'Strokes over par in disc golf at Liberty'}},
{'id':'lunch', 'description':{'en-US':'Lunch having been eaten',
'en-FR': 'altlunch'}}]}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar9'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar9', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('performance', rsp)
self.assertIn('steps', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('pong.1,dg.10,lunch.4', rsp)
self.assertIn('Net pong matches won', rsp)
self.assertIn('Strokes over par in disc golf at Liberty', rsp)
rsp_dict = json.loads(rsp)
self.assertEqual(len(rsp_dict['definition']['name'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['steps'][0]['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['steps'][1]['description'].keys()), 1)
self.assertEqual(len(rsp_dict['definition']['steps'][2]['description'].keys()), 1)
def test_get_crp_sequencing(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar10',
'definition': {'name': {'en-US':'testname2'},'description': {'en-US':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'sequencing',
'correctResponsesPattern': ['lou,tom,andy,aaron'],'choices':[{'id': 'lou',
'description': {'en-US':'Lou'}},{'id': 'tom','description':{'en-US': 'Tom'}},
{'id':'andy', 'description':{'en-US':'Andy'}},{'id':'aaron', 'description':{'en-US':'Aaron'}}]}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar10'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar10', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('sequencing', rsp)
self.assertIn('choices', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('lou,tom,andy,aaron', rsp)
def test_get_crp_numeric(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id':'act:foobar11',
'definition': {'name': {'en-US':'testname2'},'description': {'en-US':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'numeric','correctResponsesPattern': ['4'],
'extensions': {'ext:key1': 'value1', 'ext:key2': 'value2','ext:key3': 'value3'}}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar11'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar11', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('numeric', rsp)
self.assertIn('4', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
self.assertIn('extensions', rsp)
self.assertIn('key1', rsp)
self.assertIn('value1', rsp)
self.assertIn('key2', rsp)
self.assertIn('value2', rsp)
self.assertIn('key3', rsp)
self.assertIn('value3', rsp)
def test_get_crp_other(self):
st = json.dumps({"actor":{"objectType":"Agent","mbox": "mailto:[email protected]"},
"verb":{"id": "http://adlnet.gov/expapi/verbs/assess","display": {"en-US":"assessed"}},
"object":{'objectType': 'Activity', 'id': 'act:foobar12',
'definition': {'name': {'en-US':'testname2'},'description': {'en-US':'testdesc2'},
'type': 'http://adlnet.gov/expapi/activities/cmi.interaction','interactionType': 'other',
'correctResponsesPattern': ['(35.937432,-86.868896)']}}})
st_post = self.client.post(reverse(statements), st, content_type="application/json", Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(st_post.status_code, 200)
response = self.client.get(reverse(activities), {'activityId': 'act:foobar12'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
rsp = response.content
self.assertEqual(response.status_code, 200)
self.assertIn('act:foobar12', rsp)
self.assertIn('http://adlnet.gov/expapi/activities/cmi.interaction', rsp)
self.assertIn('other', rsp)
self.assertIn('(35.937432,-86.868896)', rsp)
self.assertIn('en-US', rsp)
self.assertIn('testname2', rsp)
self.assertIn('testdesc2', rsp)
self.assertIn('correctResponsesPattern', rsp)
def test_get_wrong_activity(self):
response = self.client.get(reverse(activities), {'activityId': 'act:act:foo'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 404)
<|fim▁hole|> response = self.client.head(reverse(activities), {'activityId': 'act:act:foo'}, Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 404)
def test_get_no_activity(self):
response = self.client.get(reverse(activities), Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 400)
def test_post(self):
response = self.client.post(reverse(activities), {'activityId':'act:my_activity'},
content_type='application/x-www-form-urlencoded', Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 405)
def test_delete(self):
response = self.client.delete(reverse(activities), {'activityId':'act:my_activity'},
content_type='application/x-www-form-urlencoded', Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 405)
def test_put(self):
response = self.client.put(reverse(activities), {'activityId':'act:my_activity'},
content_type='application/x-www-form-urlencoded', Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)
self.assertEqual(response.status_code, 405)<|fim▁end|> | def test_head_wrong_activity(self): |
<|file_name|>order.py<|end_file_name|><|fim▁begin|>from ..cw_model import CWModel
class Order(CWModel):
def __init__(self, json_dict=None):
self.id = None # (Integer)
self.company = None # *(CompanyReference)
self.contact = None # (ContactReference)
self.phone = None # (String)
self.phoneExt = None # (String)
self.email = None # (String)
self.site = None # (SiteReference)
self.status = None # *(OrderStatusReference)
self.opportunity = None # (OpportunityReference)
self.orderDate = None # (String)
self.dueDate = None # (String)
self.billingTerms = None # (BillingTermsReference)
self.taxCode = None # (TaxCodeReference)
self.poNumber = None # (String(50))
self.locationId = None # (Integer)
self.businessUnitId = None # (Integer)
self.salesRep = None # *(MemberReference)
self.notes = None # (String)
self.billClosedFlag = None # (Boolean)
self.billShippedFlag = None # (Boolean)
self.restrictDownpaymentFlag = None # (Boolean)
<|fim▁hole|> self.topCommentFlag = None # (Boolean)
self.bottomCommentFlag = None # (Boolean)
self.shipToCompany = None # (CompanyReference)
self.shipToContact = None # (ContactReference)
self.shipToSite = None # (SiteReference)
self.billToCompany = None # (CompanyReference)
self.billToContact = None # (ContactReference)
self.billToSite = None # (SiteReference)
self.productIds = None # (Integer[])
self.documentIds = None # (Integer[])
self.invoiceIds = None # (Integer[])
self.configIds = None # (Integer[])
self.total = None # (Number)
self.taxTotal = None # (Number)
self._info = None # (Metadata)
# initialize object with json dict
super().__init__(json_dict)<|fim▁end|> | self.description = None # (String)
|
<|file_name|>fix.js<|end_file_name|><|fim▁begin|>$(document).ready(function() {
///*определение ширины скролбара
// создадим элемент с прокруткой
var div = document.createElement('div');
div.style.overflowY = 'scroll';
div.style.width = '50px';
div.style.height = '50px';
div.style.position = 'absolute';
div.style.zIndex = '-1';
// при display:none размеры нельзя узнать
// нужно, чтобы элемент был видим,
// visibility:hidden - можно, т.к. сохраняет геометрию
div.style.visibility = 'hidden';
document.body.appendChild(div);
var scrollWidth = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
//*/
var fixedblock = $('#fixed');
var stick_state = false;
function fxm() {
if ($(window).width() > 640-scrollWidth) {
fixedblock.trigger("sticky_kit:detach");
fixedblock.stick_in_parent({
parent: '#main .columns',
offset_top: 30,
inner_scrolling: false
});
fixedblock.stick_in_parent()
.on("sticky_kit:stick", function(e) {
stick_state = true;
})
.on("sticky_kit:unstick", function(e) {
stick_state = false;
});
} else {
fixedblock.trigger("sticky_kit:detach");
}
}
fxm();
var navigation = document.getElementById('navigation');
if (navigation) {
var new_fix_elem = document.createElement('div');
new_fix_elem.setAttribute('class', 'nav__bounce__element');
navigation.parentNode.insertBefore(new_fix_elem, navigation);
}
var my__abs__list = document.querySelector('.my__abs__list');
var count_change = -1;
var fix_flag = false;
var navleft = navigation.querySelector('.block--left .menu');
/* шаг скролла */
var topless = 0;
var difference = 0;
function navig_fixit() {
var cont_top = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
var docHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
difference = cont_top - topless;
topless = cont_top;
if (navigation) {
if ($(window).width() > 768 - scrollWidth) {
var height = navigation.offsetHeight;
var rect = navigation.getBoundingClientRect();
var rect2 = new_fix_elem.getBoundingClientRect();
navigation.style.left = rect.left + 'px';
navigation.style.width = new_fix_elem.offsetWidth + 'px';
if (navleft.classList.contains('open') === true) {
var rectus = navleft.getBoundingClientRect();
console.log(rectus.height);
if (navigation.style.marginTop == '') {
navigation.style.marginTop = '0px';
}
var ms = parseInt(navigation.style.marginTop);
ms = Math.abs(ms);
ms += difference;
if (ms >= 0) {
var x_height = height + rectus.height - 50;
if (ms <= x_height - docHeight) {
navigation.style.marginTop = -ms+'px';
} else {
if (difference < 0) {
navigation.style.marginTop = -ms+'px';
}
}
}
/* navigation.classList.remove('fixed'); */
new_fix_elem.style.height = '0px';
return false;<|fim▁hole|> if (rect2.top > count_change) {
navigation.classList.add('fixed');
new_fix_elem.style.height = height + 'px';
fix_flag = true;
fixedblock.css('margin-top', height + 'px');
if (stick_state === false) {
fixedblock.css('margin-top', '0px');
}
} else {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
fixedblock.css('margin-top', '0px');
}
}
} else {
if (rect2.top > count_change) {
navigation.classList.add('fixed');
new_fix_elem.style.height = height + 'px';
fix_flag = true;
fixedblock.css('margin-top', height + 'px');
if (stick_state === false) {
fixedblock.css('margin-top', '0px');
}
if (rect2.top > 0) {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
}
} else {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
fixedblock.css('margin-top', '0px');
}
}
count_change = rect2.top;
} else {
navigation.classList.remove('fixed');
navigation.style = '';
new_fix_elem.style.height = '0px';
my__abs__list.classList.remove('active');
}
}
}
navig_fixit();
//debounce
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Использование
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
navig_fixit();
fxm();
if (navigation) {
navigation.classList.remove('active');
}
}, 200);
/* var myEfficientFn2 = debounce(function() {
// All the taxing stuff you do
fxm();
}, 250); */
window.addEventListener('resize', myEfficientFn);
/* window.addEventListener('scroll', myEfficientFn2); */
$(window).scroll(function() {
navig_fixit();
});
});<|fim▁end|> | }
if (fix_flag === false) {
if (rect2.top + height*2 < 0) { |
<|file_name|>lint-obsolete-attr.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or<|fim▁hole|>// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// When denying at the crate level, be sure to not get random warnings from the
// injected intrinsics by the compiler.
#![deny(attribute_usage)]
#![allow(dead_code)]
#[abi="stdcall"] extern {} //~ ERROR: obsolete attribute
#[fixed_stack_segment] fn f() {} //~ ERROR: obsolete attribute
fn main() {}<|fim▁end|> | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
<|file_name|>get.go<|end_file_name|><|fim▁begin|>package eureka
import (
"encoding/xml"
"strings"
)
func (c *Client) GetApplications() (*Applications, error) {
response, err := c.Get("apps")
if err != nil {
return nil, err
}
var applications *Applications = new(Applications)
err = xml.Unmarshal(response.Body, applications)
return applications, err
}
func (c *Client) GetApplication(appId string) (*Application, error) {
values := []string{"apps", appId}
path := strings.Join(values, "/")
response, err := c.Get(path)
if err != nil {
return nil, err
}
var application *Application = new(Application)
err = xml.Unmarshal(response.Body, application)
return application, err
}
func (c *Client) GetInstance(appId, instanceId string) (*InstanceInfo, error) {
values := []string{"apps", appId, instanceId}
path := strings.Join(values, "/")
response, err := c.Get(path)
if err != nil {
return nil, err
}
var instance *InstanceInfo = new(InstanceInfo)
err = xml.Unmarshal(response.Body, instance)
return instance, err
}
func (c *Client) GetVIP(vipId string) (*Applications, error) {
values := []string{"vips", vipId}
path := strings.Join(values, "/")
response, err := c.Get(path)
if err != nil {
return nil, err
}
var applications *Applications = new(Applications)
err = xml.Unmarshal(response.Body, applications)
return applications, err
}
func (c *Client) GetSVIP(svipId string) (*Applications, error) {
values := []string{"svips", svipId}
path := strings.Join(values, "/")
response, err := c.Get(path)
if err != nil {
return nil, err<|fim▁hole|>}<|fim▁end|> | }
var applications *Applications = new(Applications)
err = xml.Unmarshal(response.Body, applications)
return applications, err |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | __author__ = 'donstrata' |
<|file_name|>gene_test.go<|end_file_name|><|fim▁begin|>package alignmentprofile
import "testing"
func TestGeneMatching(t *testing.T) {
matchingCases := []struct {
g Gene
s string
}{<|fim▁hole|> {Gene("A"), "a"},
{Gene("A"), "A"},
{Gene("A"), " a "},
{Gene("A"), "A "},
}
for _, c := range matchingCases {
if !c.g.Matches(c.s) {
t.Errorf("%v doesn't match %v", c.g, c.s)
}
}
mismatchCases := []struct {
g Gene
s string
}{
{Gene("A"), "B"},
{Gene("A"), "b"},
{Gene("A"), "A1"},
{Gene("A"), " A1"},
{Gene("A"), " A 1"},
}
for _, c := range mismatchCases {
if c.g.Matches(c.s) {
t.Errorf("%v matches %v", c.g, c.s)
}
}
}<|fim▁end|> | |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>"""
This file includes commonly used utilities for this app.
"""
from datetime import datetime
today = datetime.now()
year = today.year
month = today.month
day = today.day<|fim▁hole|>
def front_image(instance, filename):
# file will be uploaded to MEDIA_ROOT/product_imgs/owner_<id>/product_<id>/Y/m/d/front/<filename>
return 'product_imgs/owner_{0}/product_{1}/{2}/{3}/{4}/front/{5}'.format(instance.owner.id, instance.slug, year, month, day, filename)
def back_image(instance, filename):
# file will be uploaded to MEDIA_ROOT/product_imgs/owner_<id>/product_<id>/Y/m/d/back/<filename>
return 'product_imgs/owner_{0}/product_{1}/{2}/{3}/{4}/back/{5}'.format(instance.owner.id, instance.slug, year, month, day, filename)
'''
def front_design_image(instance, filename):
# file will be uploaded to MEDIA_ROOT/product_imgs/designer_<id>/design_product_<id>/Y/m/d/front/<filename>
return 'product_imgs/designer_{0}/design_product_{1}/{2}/{3}/{4}/front/{5}'.format(instance.designer.id, instance.id, year, month, day, filename)
def back_design_image(instance, filename):
# file will be uploaded to MEDIA_ROOT/product_imgs/designer_<id>/design_product_<id>/Y/m/d/back/<filename>
return 'product_imgs/designer_{0}/design_product_{1}/{2}/{3}/{4}/back/{5}'.format(instance.designer.id, instance.id, year, month, day, filename)
'''
def fill_category_tree(model, deep=0, parent_id=0, tree=[]):
'''
NAME::
fill_category_tree
DESCRIPTION::
一般用来针对带有parent产品分类表字段的进行遍历,并生成树形结构
PARAMETERS::
:param model: 被遍历的model,具有parent属性
:param deep: 本例中,为了明确表示父子的层次关系,用短线---的多少来表示缩进
:param parent_id: 表示从哪个父类开始,=0表示从最顶层开始
:param tree: 要生成的树形tuple
RETURN::
这里是不需要返回值的,但是如果某个调用中需要可以画蛇添足一下
USAGE::
调用时,可以这样:
choices = [()]
fill_topic_tree(choices=choices)
这里使用[],而不是(),是因为只有[],才能做为“引用”类型传递数据。
'''
if parent_id == 0:
ts = model.objects.filter(parent = None)
# tree[0] += ((None, '选择产品类型'),)
for t in ts:
tmp = [()]
fill_category_tree(4, t.id, tmp)
tree[0] += ((t.id, '-'*deep + t.name,),)
for tt in tmp[0]:
tree[0] += (tt,)
else:
ts = Category.objects.filter(parent_id = parent_id)
for t in ts:
tree[0] += ((t.id, '-'*deep + t.name,),)
fill_category_tree(deep + 4, t.id, tree)
return tree<|fim▁end|> |
# Following are for images upload helper functions. The first two are used for product upload for the front and back.
# The last two are used for design product upload for the front and back. |
<|file_name|>issue-333.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
fn quux<T>(x: T) -> T { let f = id::<T>; return f(x); }
fn id<T>(x: T) -> T { return x; }
pub fn main() { assert!((quux(10) == 10)); }<|fim▁end|> | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
<|file_name|>background.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | declare var chrome: any; |
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>/*
* Qt REST Client
* Copyright (C) 2014 Emílio Simões
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QDebug>
#include "autotest.h"
#if 1
// This is all you need to run all the tests
TEST_MAIN
#else
// Or supply your own main function
int main(int argc, char* argv[]) {<|fim▁hole|> int failures = AutoTest::run(argc, argv);
if (failures == 0) {
qDebug() << "ALL TESTS PASSED";
} else {
qDebug() << failures << " TESTS FAILED!";
}
return failures;
}
#endif<|fim▁end|> | |
<|file_name|>skiplist_tests.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2014-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <util.h>
#include <test/test_bitcoin.h>
#include <vector>
#include <boost/test/unit_test.hpp>
#define SKIPLIST_LENGTH 300000
BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(skiplist_test)
{
std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH);
for (int i=0; i<SKIPLIST_LENGTH; i++) {
vIndex[i].nHeight = i;
vIndex[i].pprev = (i == 0) ? nullptr : &vIndex[i - 1];
vIndex[i].BuildSkip();
}
for (int i=0; i<SKIPLIST_LENGTH; i++) {
if (i > 0) {
BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]);
BOOST_CHECK(vIndex[i].pskip->nHeight < i);
} else {
BOOST_CHECK(vIndex[i].pskip == nullptr);
}
}
for (int i=0; i < 1000; i++) {
int from = InsecureRandRange(SKIPLIST_LENGTH - 1);
int to = InsecureRandRange(from + 1);
BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]);
BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]);
BOOST_CHECK(vIndex[from].GetAncestor(0) == vIndex.data());
}
}
BOOST_AUTO_TEST_CASE(getlocator_test)
{
// Build a main chain 100000 blocks long.
std::vector<uint256> vHashMain(100000);
std::vector<CBlockIndex> vBlocksMain(100000);
for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height, so we can quickly check the distances.
vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : nullptr;
vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].nHeight);
BOOST_CHECK(vBlocksMain[i].pprev == nullptr || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1);
}<|fim▁hole|> std::vector<uint256> vHashSide(50000);
std::vector<CBlockIndex> vBlocksSide(50000);
for (unsigned int i=0; i<vBlocksSide.size(); i++) {
vHashSide[i] = ArithToUint256(i + 50000 + (arith_uint256(1) << 128)); // Add 1<<128 to the hashes, so GetLow64() still returns the height.
vBlocksSide[i].nHeight = i + 50000;
vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : (vBlocksMain.data()+49999);
vBlocksSide[i].phashBlock = &vHashSide[i];
vBlocksSide[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].nHeight);
BOOST_CHECK(vBlocksSide[i].pprev == nullptr || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1);
}
// Build a CChain for the main branch.
CChain chain;
chain.SetTip(&vBlocksMain.back());
// Test 100 random starting points for locators.
for (int n=0; n<100; n++) {
int r = InsecureRandRange(150000);
CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000];
CBlockLocator locator = chain.GetLocator(tip);
// The first result must be the block itself, the last one must be genesis.
BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash());
BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash());
// Entries 1 through 11 (inclusive) go back one step each.
for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i]).GetLow64(), tip->nHeight - i);
}
// The further ones (excluding the last one) go back with exponential steps.
unsigned int dist = 2;
for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i - 1]).GetLow64() - UintToArith256(locator.vHave[i]).GetLow64(), dist);
dist *= 2;
}
}
}
BOOST_AUTO_TEST_CASE(findearliestatleast_test)
{
std::vector<uint256> vHashMain(100000);
std::vector<CBlockIndex> vBlocksMain(100000);
for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height
vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : nullptr;
vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip();
if (i < 10) {
vBlocksMain[i].nTime = i;
vBlocksMain[i].nTimeMax = i;
} else {
// randomly choose something in the range [MTP, MTP*2]
int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast();
int r = InsecureRandRange(medianTimePast);
vBlocksMain[i].nTime = r + medianTimePast;
vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax);
}
}
// Check that we set nTimeMax up correctly.
unsigned int curTimeMax = 0;
for (unsigned int i=0; i<vBlocksMain.size(); ++i) {
curTimeMax = std::max(curTimeMax, vBlocksMain[i].nTime);
BOOST_CHECK(curTimeMax == vBlocksMain[i].nTimeMax);
}
// Build a CChain for the main branch.
CChain chain;
chain.SetTip(&vBlocksMain.back());
// Verify that FindEarliestAtLeast is correct.
for (unsigned int i=0; i<10000; ++i) {
// Pick a random element in vBlocksMain.
int r = InsecureRandRange(vBlocksMain.size());
int64_t test_time = vBlocksMain[r].nTime;
CBlockIndex *ret = chain.FindEarliestAtLeast(test_time);
BOOST_CHECK(ret->nTimeMax >= test_time);
BOOST_CHECK((ret->pprev==nullptr) || ret->pprev->nTimeMax < test_time);
BOOST_CHECK(vBlocksMain[r].GetAncestor(ret->nHeight) == ret);
}
}
BOOST_AUTO_TEST_CASE(findearliestatleast_edge_test)
{
std::list<CBlockIndex> blocks;
for (unsigned int timeMax : {100, 100, 100, 200, 200, 200, 300, 300, 300}) {
CBlockIndex* prev = blocks.empty() ? nullptr : &blocks.back();
blocks.emplace_back();
blocks.back().nHeight = prev ? prev->nHeight + 1 : 0;
blocks.back().pprev = prev;
blocks.back().BuildSkip();
blocks.back().nTimeMax = timeMax;
}
CChain chain;
chain.SetTip(&blocks.back());
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(50)->nHeight, 0);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(100)->nHeight, 0);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(150)->nHeight, 3);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(200)->nHeight, 3);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(250)->nHeight, 6);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(300)->nHeight, 6);
BOOST_CHECK(!chain.FindEarliestAtLeast(350));
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(0)->nHeight, 0);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(-1)->nHeight, 0);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(std::numeric_limits<int64_t>::min())->nHeight, 0);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(std::numeric_limits<unsigned int>::min())->nHeight, 0);
BOOST_CHECK_EQUAL(chain.FindEarliestAtLeast(-int64_t(std::numeric_limits<unsigned int>::max()) - 1)->nHeight, 0);
BOOST_CHECK(!chain.FindEarliestAtLeast(std::numeric_limits<int64_t>::max()));
BOOST_CHECK(!chain.FindEarliestAtLeast(std::numeric_limits<unsigned int>::max()));
BOOST_CHECK(!chain.FindEarliestAtLeast(int64_t(std::numeric_limits<unsigned int>::max()) + 1));
}
BOOST_AUTO_TEST_SUITE_END()<|fim▁end|> |
// Build a branch that splits off at block 49999, 50000 blocks long. |
<|file_name|>media_queries.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::ascii::AsciiExt;
use cssparser::{Token, Parser, Delimiter};
use geom::size::TypedSize2D;
use properties::longhands;
use util::geometry::{Au, ViewportPx};
use values::{computed, specified};
#[derive(Debug, PartialEq)]
pub struct MediaQueryList {
media_queries: Vec<MediaQuery>
}
#[derive(PartialEq, Eq, Copy, Debug)]
pub enum Range<T> {
Min(T),
Max(T),
//Eq(T), // FIXME: Implement parsing support for equality then re-enable this.
}
impl<T: Ord> Range<T> {
fn evaluate(&self, value: T) -> bool {
match *self {
Range::Min(ref width) => { value >= *width },
Range::Max(ref width) => { value <= *width },
//Range::Eq(ref width) => { value == *width },
}
}
}
#[derive(PartialEq, Eq, Copy, Debug)]
pub enum Expression {
Width(Range<Au>),
}
#[derive(PartialEq, Eq, Copy, Debug)]
pub enum Qualifier {
Only,
Not,
}
#[derive(Debug, PartialEq)]
pub struct MediaQuery {
qualifier: Option<Qualifier>,
media_type: MediaQueryType,
expressions: Vec<Expression>,
}
impl MediaQuery {
pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType,
expressions: Vec<Expression>) -> MediaQuery {
MediaQuery {
qualifier: qualifier,
media_type: media_type,
expressions: expressions,
}
}
}
#[derive(PartialEq, Eq, Copy, Debug)]
pub enum MediaQueryType {
All, // Always true
MediaType(MediaType),
}
#[derive(PartialEq, Eq, Copy, Debug)]
pub enum MediaType {
Screen,
Print,
Unknown,
}
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub struct Device {
pub media_type: MediaType,
pub viewport_size: TypedSize2D<ViewportPx, f32>,
}
impl Device {
pub fn new(media_type: MediaType, viewport_size: TypedSize2D<ViewportPx, f32>) -> Device {
Device {
media_type: media_type,
viewport_size: viewport_size,
}
}
}
fn parse_non_negative_length(input: &mut Parser) -> Result<Au, ()> {
let length = try!(specified::Length::parse_non_negative(input));
// http://dev.w3.org/csswg/mediaqueries3/ - Section 6
// em units are relative to the initial font-size.
let initial_font_size = longhands::font_size::get_initial_value();
Ok(computed::compute_Au_with_font_size(length, initial_font_size, initial_font_size))
}
impl Expression {
fn parse(input: &mut Parser) -> Result<Expression, ()> {
try!(input.expect_parenthesis_block());
input.parse_nested_block(|input| {
let name = try!(input.expect_ident());
try!(input.expect_colon());
// TODO: Handle other media features
match_ignore_ascii_case! { name,
"min-width" => {
Ok(Expression::Width(Range::Min(try!(parse_non_negative_length(input)))))
},
"max-width" => {
Ok(Expression::Width(Range::Max(try!(parse_non_negative_length(input)))))
}
_ => Err(())
}
})
}
}
impl MediaQuery {
fn parse(input: &mut Parser) -> Result<MediaQuery, ()> {
let mut expressions = vec![];
let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() {
Some(Qualifier::Only)
} else if input.try(|input| input.expect_ident_matching("not")).is_ok() {
Some(Qualifier::Not)
} else {
None
};
let media_type;
if let Ok(ident) = input.try(|input| input.expect_ident()) {
media_type = match_ignore_ascii_case! { ident,
"screen" => MediaQueryType::MediaType(MediaType::Screen),
"print" => MediaQueryType::MediaType(MediaType::Print),
"all" => MediaQueryType::All
_ => MediaQueryType::MediaType(MediaType::Unknown)
}
} else {
// Media type is only optional if qualifier is not specified.
if qualifier.is_some() {
return Err(())
}
media_type = MediaQueryType::All;
// Without a media type, require at least one expression
expressions.push(try!(Expression::parse(input)));
}
// Parse any subsequent expressions
loop {
if input.try(|input| input.expect_ident_matching("and")).is_err() {
return Ok(MediaQuery::new(qualifier, media_type, expressions))
}
expressions.push(try!(Expression::parse(input)))
}
}
}
pub fn parse_media_query_list(input: &mut Parser) -> MediaQueryList {
let queries = if input.is_exhausted() {
vec![MediaQuery::new(None, MediaQueryType::All, vec!())]
} else {
let mut media_queries = vec![];
loop {
media_queries.push(
input.parse_until_before(Delimiter::Comma, MediaQuery::parse)
.unwrap_or(MediaQuery::new(Some(Qualifier::Not),
MediaQueryType::All,
vec!())));
match input.next() {
Ok(Token::Comma) => continue,
Ok(_) => unreachable!(),
Err(()) => break,
}
}
media_queries
};
MediaQueryList { media_queries: queries }
}
impl MediaQueryList {
pub fn evaluate(&self, device: &Device) -> bool {
// Check if any queries match (OR condition)
self.media_queries.iter().any(|mq| {
// Check if media matches. Unknown media never matches.
let media_match = match mq.media_type {
MediaQueryType::MediaType(MediaType::Unknown) => false,
MediaQueryType::MediaType(media_type) => media_type == device.media_type,
MediaQueryType::All => true,
};
// Check if all conditions match (AND condition)
let query_match = media_match && mq.expressions.iter().all(|expression| {
match expression {
&Expression::Width(value) => value.evaluate(
Au::from_frac_px(device.viewport_size.to_untyped().width as f64)),
}
});
// Apply the logical NOT qualifier to the result
match mq.qualifier {
Some(Qualifier::Not) => !query_match,
_ => query_match,
}
})
}
}
#[cfg(test)]
mod tests {
use geom::size::TypedSize2D;
use util::geometry::Au;
use stylesheets::{iter_stylesheet_media_rules, iter_stylesheet_style_rules, Stylesheet};
use stylesheets::Origin;
use super::*;
use url::Url;
use std::borrow::ToOwned;
fn test_media_rule<F>(css: &str, callback: F) where F: Fn(&MediaQueryList, &str) {
let url = Url::parse("http://localhost").unwrap();
let stylesheet = Stylesheet::from_str(css, url, Origin::Author);
let mut rule_count: int = 0;
iter_stylesheet_media_rules(&stylesheet, |rule| {
rule_count += 1;
callback(&rule.media_queries, css);
});
assert!(rule_count > 0);
}
fn media_query_test(device: &Device, css: &str, expected_rule_count: int) {
let url = Url::parse("http://localhost").unwrap();
let ss = Stylesheet::from_str(css, url, Origin::Author);
let mut rule_count: int = 0;
iter_stylesheet_style_rules(&ss, device, |_| rule_count += 1);
assert!(rule_count == expected_rule_count, css.to_owned());
}
#[test]
fn test_mq_empty() {
test_media_rule("@media { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_mq_screen() {
test_media_rule("@media screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media only screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media not screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_mq_print() {
test_media_rule("@media print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media only print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media not print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_mq_unknown() {
test_media_rule("@media fridge { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media only glass { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media not wood { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_mq_all() {
test_media_rule("@media all { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media only all { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media not all { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_mq_or() {
test_media_rule("@media screen, print { }", |list, css| {
assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0];
assert!(q0.qualifier == None, css.to_owned());
assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q0.expressions.len() == 0, css.to_owned());
let q1 = &list.media_queries[1];
assert!(q1.qualifier == None, css.to_owned());
assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q1.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_mq_default_expressions() {
test_media_rule("@media (min-width: 100px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"),
}
});
test_media_rule("@media (max-width: 43px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)),
_ => panic!("wrong expression type"),
}
});
}
#[test]
fn test_mq_expressions() {
test_media_rule("@media screen and (min-width: 100px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"),
}
});
test_media_rule("@media print and (max-width: 43px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)),
_ => panic!("wrong expression type"),
}
});<|fim▁hole|> assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(52)),
_ => panic!("wrong expression type"),
}
});
}
#[test]
fn test_mq_multiple_expressions() {
test_media_rule("@media (min-width: 100px) and (max-width: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 2, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"),
}
match q.expressions[1] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(200)),
_ => panic!("wrong expression type"),
}
});
test_media_rule("@media not screen and (min-width: 100px) and (max-width: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 2, css.to_owned());
match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"),
}
match q.expressions[1] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(200)),
_ => panic!("wrong expression type"),
}
});
}
#[test]
fn test_mq_malformed_expressions() {
test_media_rule("@media (min-width: 100blah) and (max-width: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media screen and (height: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media (min-width: 30em foo bar) {}", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media not {}", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media not (min-width: 300px) {}", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media , {}", |list, css| {
assert!(list.media_queries.len() == 2, css.to_owned());
let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
let q = &list.media_queries[1];
assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media screen 4px, print {}", |list, css| {
assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0];
assert!(q0.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q0.media_type == MediaQueryType::All, css.to_owned());
assert!(q0.expressions.len() == 0, css.to_owned());
let q1 = &list.media_queries[1];
assert!(q1.qualifier == None, css.to_owned());
assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q1.expressions.len() == 0, css.to_owned());
});
test_media_rule("@media screen, {}", |list, css| {
assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0];
assert!(q0.qualifier == None, css.to_owned());
assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q0.expressions.len() == 0, css.to_owned());
let q1 = &list.media_queries[1];
assert!(q1.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q1.media_type == MediaQueryType::All, css.to_owned());
assert!(q1.expressions.len() == 0, css.to_owned());
});
}
#[test]
fn test_matching_simple() {
let device = Device {
media_type: MediaType::Screen,
viewport_size: TypedSize2D(200.0, 100.0),
};
media_query_test(&device, "@media not all { a { color: red; } }", 0);
media_query_test(&device, "@media not screen { a { color: red; } }", 0);
media_query_test(&device, "@media not print { a { color: red; } }", 1);
media_query_test(&device, "@media unknown { a { color: red; } }", 0);
media_query_test(&device, "@media not unknown { a { color: red; } }", 1);
media_query_test(&device, "@media { a { color: red; } }", 1);
media_query_test(&device, "@media screen { a { color: red; } }", 1);
media_query_test(&device, "@media print { a { color: red; } }", 0);
}
#[test]
fn test_matching_width() {
let device = Device {
media_type: MediaType::Screen,
viewport_size: TypedSize2D(200.0, 100.0),
};
media_query_test(&device, "@media { a { color: red; } }", 1);
media_query_test(&device, "@media (min-width: 50px) { a { color: red; } }", 1);
media_query_test(&device, "@media (min-width: 150px) { a { color: red; } }", 1);
media_query_test(&device, "@media (min-width: 300px) { a { color: red; } }", 0);
media_query_test(&device, "@media screen and (min-width: 50px) { a { color: red; } }", 1);
media_query_test(&device, "@media screen and (min-width: 150px) { a { color: red; } }", 1);
media_query_test(&device, "@media screen and (min-width: 300px) { a { color: red; } }", 0);
media_query_test(&device, "@media not screen and (min-width: 50px) { a { color: red; } }", 0);
media_query_test(&device, "@media not screen and (min-width: 150px) { a { color: red; } }", 0);
media_query_test(&device, "@media not screen and (min-width: 300px) { a { color: red; } }", 1);
media_query_test(&device, "@media (max-width: 50px) { a { color: red; } }", 0);
media_query_test(&device, "@media (max-width: 150px) { a { color: red; } }", 0);
media_query_test(&device, "@media (max-width: 300px) { a { color: red; } }", 1);
media_query_test(&device, "@media screen and (min-width: 50px) and (max-width: 100px) { a { color: red; } }", 0);
media_query_test(&device, "@media screen and (min-width: 250px) and (max-width: 300px) { a { color: red; } }", 0);
media_query_test(&device, "@media screen and (min-width: 50px) and (max-width: 250px) { a { color: red; } }", 1);
media_query_test(&device, "@media not screen and (min-width: 50px) and (max-width: 100px) { a { color: red; } }", 1);
media_query_test(&device, "@media not screen and (min-width: 250px) and (max-width: 300px) { a { color: red; } }", 1);
media_query_test(&device, "@media not screen and (min-width: 50px) and (max-width: 250px) { a { color: red; } }", 0);
media_query_test(&device, "@media not screen and (min-width: 3.1em) and (max-width: 6em) { a { color: red; } }", 1);
media_query_test(&device, "@media not screen and (min-width: 16em) and (max-width: 19.75em) { a { color: red; } }", 1);
media_query_test(&device, "@media not screen and (min-width: 3em) and (max-width: 250px) { a { color: red; } }", 0);
}
#[test]
fn test_matching_invalid() {
let device = Device {
media_type: MediaType::Screen,
viewport_size: TypedSize2D(200.0, 100.0),
};
media_query_test(&device, "@media fridge { a { color: red; } }", 0);
media_query_test(&device, "@media screen and (height: 100px) { a { color: red; } }", 0);
media_query_test(&device, "@media not print and (width: 100) { a { color: red; } }", 0);
}
}<|fim▁end|> |
test_media_rule("@media fridge and (max-width: 52px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; |
<|file_name|>pysickle.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
'''
Copyright (C) 2014 Janina Mass
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
'''
import sys
import getopt
import subprocess
import threading
import os
import shutil
import matplotlib
#don't use X:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy
from distutils import spawn
#########################
# last update:
# Fr 16 Mai 2014 14:25:46 CEST
# [JMass]
#########################
global GAP
GAP = "-"
class Alignment(object):
def __init__(self, id=None, fasta = None, members = []):
self.id = id
self.fasta = fasta
self.members = []
self.gapPos = []
self.mismatchPos = []
self.matchPos = []
self.matchGapPos = []
self.attachSequences()
self.calcNumbers()
def __repr__(self):
ids = self.members
return("Alignment:{},{}".format(self.id, ids))
def __len__(self):
try:
return(len(self.members[0].sequence))
except TypeError as e:
sys.stderr.write(e)
sys.stderr.write("attachSequences first")
return(0)
def getStats(self):
res = ""
res+="{},{},{},{},{},{}".format(len(self.matchPos),len(self.matchGapPos),len(self.mismatchPos),len(self)-len(self.gapPos),len(self.gapPos),len(self) )
return(res)
def attachSequences(self):
fp = FastaParser()
print("FASTA:", self.fasta)
for f in fp.read_fasta(self.fasta):
newSeq = Sequence(id = f[0], sequence = f[1])
self.members.append(newSeq)
def calcNumbers(self):
for i in range(0, len(self)):
curpos = [m.sequence[i] for m in self.members]
if GAP in curpos:
#dynamic penalty:
tmp = "".join(curpos)
gappyness = tmp.count(GAP)/float(len(self.members))
half = len(self.members)/2.0
if gappyness > half:
toPunish = [m for m in self.members if m.sequence[i]!=GAP]
for t in toPunish:
t._dynamicPenalty+=gappyness
elif gappyness < half:
#punish gappers
toPunish = [m for m in self.members if m.sequence[i]==GAP]
for t in toPunish:
t._dynamicPenalty+=1-gappyness
else:
pass
#/dyn penalty
self.gapPos.append(i)
#sequences that cause gaps:
gappers = [m for m in self.members if m.sequence[i] == GAP]
for m in gappers:
m.gapsCaused.append(i)
#unique gaps caused:
if len(gappers) == 1:
m.uniqueGapsCaused.append(i)
#insertions
inserters = [m for m in self.members if m.sequence[i] != GAP]
for m in inserters:
m.insertionsCaused.append(i)
#unique insertions caused:
if len(inserters) == 1:
m.uniqueInsertionsCaused.append(i)
nongap = [c for c in curpos if c != GAP]
cpset = set(curpos)
if (len(cpset) >1 and GAP not in cpset):
self.mismatchPos.append(i)
for m in self.members:
m.mismatchShared.append(i)
elif (len(cpset) == 1 and GAP not in cpset):
self.matchPos.append(i)
for m in self.members:
m.matchShared.append(i)
elif (len(cpset)==2 and GAP in cpset and len(nongap)>2):
self.matchGapPos.append(i)
def showAlignment(self, numbers = False):
res = []
mmPos = []
alignmentLength = len(self.members[0].sequence)
for i in range(0, alignmentLength):
curpos = [m.sequence[i] for m in self.members]
if numbers:
res.append(str(i)+" "+" ".join(curpos))
else:
res.append(" ".join(curpos))
return("\n".join(res))
class Sequence():
def __init__(self, id = "", sequence = None, isForeground = False):
self.id = id
self.sequence = sequence
self.isForeground = isForeground
self.insertionsCaused = [] #positions
self.uniqueInsertionsCaused = []
self.gapsCaused = []#positions
self.uniqueGapsCaused = []
self.matchShared = []
self.mismatchShared = []
self._penalty = None
# penalize by site:
# > n/2 gaps (@site): penalyze inserts by gaps/n
# < n/2 gaps (@site): penalyze gaps by inserts/n
self._dynamicPenalty = 0
def setForeground(self, bool = True):
self.isForeground = bool
def __repr__(self):
return("Sequence: {}".format(self.id))
@property
def penalty(self, uniqueGapPenalty=10, uniqueInsertPenalty=10, gapPenalty = 1, insertPenalty =1 ):
self.penalty =sum([ len(self.insertionsCaused)*insertPenalty, len(self.uniqueInsertionsCaused)*uniqueGapPenalty, len(self.gapsCaused)*gapPenalty, len(self.uniqueGapsCaused)*uniqueGapPenalty])
return(self.penalty)
def summary(self):
s = ""
s+=self.id
s+="insertionsCaused:{},uniqueInsertionsCaused:{}, gapsCaused:{}, uniqueGapsCaused:{}, penalty:{}, dynPenalty:{}".format(len(self.insertionsCaused), len(self.uniqueInsertionsCaused), len(self.gapsCaused), len(self.uniqueGapsCaused), self.penalty, self._dynamicPenalty)
return(s)
def getCustomPenalty(self,gapPenalty, uniqueGapPenalty, insertionPenalty , uniqueInsertionPenalty, mismatchPenalty, matchReward):
res = (len(self.gapsCaused)-len(self.uniqueGapsCaused))* gapPenalty\
+ len(self.uniqueGapsCaused)*uniqueGapPenalty\
+ (len(self.insertionsCaused)-len(self.uniqueInsertionsCaused)) * insertionPenalty\
+ len(self.uniqueInsertionsCaused) * uniqueInsertionPenalty\
+ len(self.mismatchShared)* mismatchPenalty\
+ len(self.matchShared) *matchReward
return(res)
class FastaParser(object):
def read_fasta(self, fasta, delim = None, asID = 0):
"""read from fasta fasta file 'fasta'
and split sequence id at 'delim' (if set)\n
example:\n
>idpart1|idpart2\n
ATGTGA\n
and 'delim="|"' returns ("idpart1", "ATGTGA")
"""
name = ""
fasta = open(fasta, "r")
while True:
line = name or fasta.readline()
if not line:
break
seq = []
while True:
name = fasta.readline()
name = name.rstrip()
if not name or name.startswith(">"):
break
else:
seq.append(name)
joinedSeq = "".join(seq)
line = line[1:]
if delim:
line = line.split(delim)[asID]
yield (line.rstrip(), joinedSeq.rstrip())
fasta.close()
###########################################
#TODO documentation
def usage():
print ("""
######################################
# pysickle.py v0.1.1
######################################
usage:
pysickle.py -f multifasta alignment
options:
-f, --fasta=FILE multifasta alignment (eg. "align.fas")
OR
-F, --fasta_dir=DIR directory with multifasta files (needs -s SUFFIX)
-s, --suffix=SUFFIX will try to work with files that end with SUFFIX (eg ".fas")
-a, --msa_tool=STR supported: "mafft" [default:"mafft"]
-i, --max_iterations=NUM force stop after NUM iterations
-n, --num_threads=NUM max number of threads to be executed in parallel [default: 1]
-m, --mode=MODE set strategy to remove outlier sequences [default: "Sites"]
available modes (not case sensitive):
"Sites", "Gaps", "uGaps","Insertions",
"uInsertions","uInstertionsGaps", "custom"
-l, --log write logfile
-h, --help prints this
only for mode "custom":
-g, --gap_penalty=NUM set gap penalty [default: 1.0]
-G, --unique_gap_penalty=NUM set unique gap penalty [default: 10.0]
-j, --insertion_penalty=NUM set insertion penalty [default:1.0]
-J, --unique_insertion_penalty=NUM set insertion penalty [default:1.0]
-M, --mismatch_penalty=NUM set mismatch penalty [default:1.0]
-r, --match_reward=NUM set match reward [default: -10.0]
""")
sys.exit(2)
############################################
def checkPath(progname):
#TODO extend
avail = ["mafft"]
if progname.lower() not in avail:
raise Exception("Program not supported. Only {} allowed.".format(",".join(avail)))
else:
path = spawn.find_executable(progname)
print("Found {} in {}\n".format(progname, path))
if not path:
raise Exception("Could not find {} on your system! Exiting. Available options:{}\n".format(progname, ",".join(avail)))
sys.exit(127)
def checkMode(mode):
avail = ["sites", "gaps", "ugaps","insertions", "uinsertions", "uinsertionsgaps", "custom"]
if mode not in avail:
raise Exception("Mode {} not available. Only {} allowed\n".format(mode, ",".join(avail)))
class TooFewSequencesException(Exception):
pass
def adjustDir(dirname, mode):
if mode == "unisertionsgaps":
abbr = "uig"
else:
abbr = mode[0:2]
return(dirname+"_"+abbr)
def getSeqToKeep(alignment, mode, gap_penalty, unique_gap_penalty, insertion_penalty, unique_insertion_penalty , mismatch_penalty, match_reward):
if mode == "sites":
toKeep = removeDynamicPenalty(alignment)
elif mode == "gaps":
toKeep = removeCustomPenalty(alignment, gapPenalty=1, uniqueGapPenalty=1, insertionPenalty =0, uniqueInsertionPenalty=0, mismatchPenalty=0, matchReward = 0)
if not toKeep:
removeDynamicPenalty(alignment)
elif mode == "ugaps":
toKeep = removeMaxUniqueGappers(alignment)
if not toKeep:
toKeep = removeDynamicPenalty(alignment)
return(toKeep)
elif mode == "insertions":
toKeep = removeCustomPenalty(alignment, gapPenalty=0, uniqueGapPenalty=0, insertionPenalty =1, uniqueInsertionPenalty=1, mismatchPenalty=0, matchReward = 0)
if not toKeep:
removeDynamicPenalty(alignment)
elif mode == "uinsertions":
toKeep = removeMaxUniqueInserters(alignment)
if not toKeep:
removeDynamicPenalty(alignment)
elif mode == "uinsertionsgaps":
toKeep = removeMaxUniqueInsertsPlusGaps(alignment)<|fim▁hole|> removeDynamicPenalty(alignment)
elif mode == "custom":
toKeep = removeCustomPenalty(alignment, gapPenalty=gap_penalty, uniqueGapPenalty=unique_gap_penalty, insertionPenalty =insertion_penalty, uniqueInsertionPenalty=unique_insertion_penalty, mismatchPenalty=mismatch_penalty, matchReward = match_reward)
if not toKeep:
removeDynamicPenalty(alignment)
else:
raise Exception("Sorry, sth went wrong at getSeqToKeep\n")
return(toKeep)
def schoenify(fasta=None, max_iter=None, finaldir = None, tmpdir = None, msa_tool = None,mode = None, logging = None, gap_penalty= None, unique_gap_penalty = None, insertion_penalty = None, unique_insertion_penalty = None, mismatch_penalty = None, match_reward = None ):
if not fasta:
raise Exception("Schoenify: Need alignment in fasta format.")
else:
arr = numpy.empty([1, 8], dtype='int32')
iteration = 0
fastabase = os.path.basename(fasta)
statsout = finaldir+os.sep+fastabase+".info"
tabout = finaldir + os.sep+fastabase+".csv"
resout = finaldir +os.sep+fastabase+".res"
if logging:
info = open(statsout,"w")
iterTab = []
headerTab = ["matches", "matchesWithGaps","mismatches"," nogap", "gaps","length","iteration","numSeq"]
alignmentstats = []
newAlignment = Alignment(fasta = fasta)
#sanity check
if len(newAlignment.members) < 3:
raise TooFewSequencesException("Need more than 2 sequences in alignment: {}\n".format(newAlignment.fasta))
if not max_iter or (max_iter > len(newAlignment.members)-2):
max_iter = len(newAlignment.members)-2
print("#max iterations:{}".format(str(max_iter)))
while (iteration < max_iter):
toKeep = getSeqToKeep(alignment = newAlignment, mode = mode, gap_penalty = gap_penalty, unique_gap_penalty = unique_gap_penalty, insertion_penalty=insertion_penalty, unique_insertion_penalty = unique_insertion_penalty, mismatch_penalty=mismatch_penalty, match_reward=match_reward)
print("# iteration: {}/{} \n".format(iteration, max_iter))
if len(toKeep) <2 :
break
res= ""
for k in toKeep:
seq ="".join([s for s in k.sequence if s !=GAP])
res+=(">{}\n{}\n".format(k.id,seq))
iterfile = tmpdir+os.sep+".".join(fastabase.split(".")[0:-1])+"."+str(iteration)
with open(iterfile+".tmp",'w') as out:
out.write(res)
#log
if logging:
for m in newAlignment.members:
info.write(m.summary()+"\n")
#log
alignmentstats.append(newAlignment.getStats().split(","))
iterTab.append((",".join(x for y in alignmentstats for x in y))+","+ str(iteration)+","+str(len(newAlignment.members)))
alignmentstats = []
iteration +=1
if msa_tool == "mafft":
proc = subprocess.Popen(["mafft","--auto", iterfile+".tmp"], stdout=open(iterfile+".out",'w'), bufsize=1)
proc.communicate()
newAlignment = Alignment(id = iterfile, fasta=iterfile+".out")
#TODO extend
if logging:
info.close()
with open(tabout, 'w') as taboutf:
taboutf.write(",".join(headerTab))
taboutf.write("\n")
taboutf.write("\n".join(iterTab ))
for i in iterTab:
row = [int(j) for j in i.split(",")]
arr = numpy.vstack((arr,numpy.array(row)))
#delete row filled with zeros
arr = numpy.delete(arr,0,0)
###########
LOCK.acquire()
plt.figure(1)
plt.suptitle(fastabase, fontsize=12)
ax = plt.subplot(3,1,1)
for i,l in zip([0,1,2,3,4,5,6,7],['match','matchWithGap','mismatch','nogap','gap','length','iteration','numSeq' ]):
if not i in [6,7]:
plt.plot(arr[:,6], arr[:,i], label=l)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels,bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ax= plt.subplot(3,1,2)
plt.plot(arr[:,6], arr[:,7])
ax.set_ylabel('count')
ax.legend(["numSeq"],bbox_to_anchor=(1.05, 0.3), loc=2, borderaxespad=0.)
ax= plt.subplot(3,1,3)
scoring =(arr[:,5]-arr[:,4])*arr[:,7]
try:
maxIndex = scoring.argmax()
with open(resout,'w')as resouth:
resouth.write("# Ranking: {}\n".format(scoring[:].argsort()[::-1]))
resouth.write("# Best set: {}".format(str(maxIndex)))
plt.plot(arr[:,6],scoring)
ax.legend(["(length-gaps)*numSeq"],bbox_to_anchor=(1.05, 0.3), loc=2, borderaxespad=0.)
ax.set_xlabel('iteration')
plt.savefig(finaldir+os.sep+fastabase+'.fun.png', bbox_inches='tight')
plt.clf()
finalfa = tmpdir+os.sep+".".join(fastabase.split(".")[0:-1])+"."+str(maxIndex)+".tmp"
finalfabase = os.path.basename(finalfa)
shutil.copy(finalfa,finaldir+os.sep+finalfabase)
except ValueError as e:
sys.stderr.write(str(e))
finally:
LOCK.release()
def removeMaxUniqueGappers(alignment):
if not isinstance(alignment, Alignment):
raise Exception("Must be of class Alignment")
s = alignment.showAlignment(numbers = True)
mxUniqueGaps = max([len(k.uniqueGapsCaused) for k in alignment.members])
keepers = [k for k in alignment.members if len(k.uniqueGapsCaused) < mxUniqueGaps]
return(keepers)
def removeMaxUniqueInserters(alignment):
if not isinstance(alignment, Alignment):
raise Exception("Must be of class Alignment")
s = alignment.showAlignment(numbers = True)
mxUniqueIns = max([len(k.uniqueInsertionsCaused) for k in alignment.members])
keepers = [k for k in alignment.members if len(k.uniqueInsertionsCaused) < mxUniqueIns]
return(keepers)
def removeMaxPenalty(alignment):
if not isinstance(alignment, Alignment):
raise Exception("Must be of class Alignment")
s = alignment.showAlignment(numbers = True)
mx = max([k.penalty for k in alignment.members])
keepers = [k for k in alignment.members if k.penalty < mx]
return(keepers)
def removeCustomPenalty(alignment, gapPenalty=None, uniqueGapPenalty=None, insertionPenalty=None, uniqueInsertionPenalty=None, mismatchPenalty=None, matchReward = None):
if not isinstance(alignment, Alignment):
raise Exception("Must be of class Alignment")
mx = max([k.getCustomPenalty( gapPenalty =gapPenalty, uniqueGapPenalty=uniqueGapPenalty, insertionPenalty=insertionPenalty, uniqueInsertionPenalty=uniqueInsertionPenalty,mismatchPenalty=mismatchPenalty, matchReward = matchReward) for k in alignment.members])
print("MAX",mx)
print([k.getCustomPenalty(gapPenalty=gapPenalty, uniqueGapPenalty=uniqueGapPenalty, insertionPenalty=insertionPenalty, uniqueInsertionPenalty=uniqueInsertionPenalty ,mismatchPenalty=mismatchPenalty, matchReward = matchReward) for k in alignment.members ])
keepers = [k for k in alignment.members if k.getCustomPenalty(gapPenalty=gapPenalty, uniqueGapPenalty=uniqueGapPenalty, insertionPenalty=insertionPenalty, uniqueInsertionPenalty=uniqueInsertionPenalty ,mismatchPenalty=mismatchPenalty, matchReward = matchReward) < mx]
return(keepers)
def removeDynamicPenalty(alignment):
if not isinstance(alignment, Alignment):
raise Exception("Must be of class Alignment")
s = alignment.showAlignment(numbers = True)
mx = max([k._dynamicPenalty for k in alignment.members])
keepers = [k for k in alignment.members if k._dynamicPenalty < mx]
return(keepers)
def removeMaxUniqueInsertsPlusGaps(alignment):
if not isinstance(alignment, Alignment):
raise Exception("Must be of class Alignment")
s = alignment.showAlignment(numbers = True)
mxUniqueIns = max([len(k.uniqueInsertionsCaused)+len(k.uniqueGapsCaused) for k in alignment.members])
keepers = [k for k in alignment.members if (len(k.uniqueInsertionsCaused)+len(k.uniqueGapsCaused)) < mxUniqueIns]
return(keepers)
class SchoenifyThread(threading.Thread):
def __init__(self,fasta, max_iter, finaldir,tmpdir, msa_tool, mode, logging, gap_penalty, unique_gap_penalty, insertion_penalty, unique_insertion_penalty, mismatch_penalty , match_reward):
super(SchoenifyThread, self).__init__()
self.fasta=fasta
self.max_iter=max_iter
self.finaldir=finaldir
self.tmpdir = tmpdir
self.msa_tool =msa_tool
self.mode = mode
self.logging = logging
#custom
self.gap_penalty = gap_penalty
self.unique_gap_penalty = unique_gap_penalty
self.insertion_penalty = insertion_penalty
self.unique_insertion_penalty = unique_insertion_penalty
self.mismatch_penalty = mismatch_penalty
self.match_reward = match_reward
def run(self):
SEMAPHORE.acquire()
try:
schoenify(fasta=self.fasta, max_iter = self.max_iter, finaldir=self.finaldir,tmpdir = self.tmpdir, msa_tool=self.msa_tool, mode = self.mode, logging = self.logging, gap_penalty= self.gap_penalty, unique_gap_penalty = self.unique_gap_penalty, insertion_penalty = self.insertion_penalty, unique_insertion_penalty = self.unique_insertion_penalty, mismatch_penalty = self.mismatch_penalty, match_reward = self.match_reward )
except TooFewSequencesException as e:
sys.stderr.write(str(e))
SEMAPHORE.release()
def getFastaList(dir=None, suffix=None):
for f in os.listdir(dir):
if f.endswith(suffix):
yield(os.sep.join([dir,f]))
def main():
fastalist = []
fastadir = None
suffix= None
max_iter = None
finaldir = None
tmpdir = None
msa_tool = "mafft"
num_threads = 1
mode = "sites"
logging = False
#custom penalty:
gap_penalty = 1.0
unique_gap_penalty = 10.0
insertion_penalty = 1.0
unique_insertion_penalty = 1.0
mismatch_penalty = 1.0
match_reward = -10.0
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "f:F:s:i:a:n:m:g:G:j:J:M:r:lh", ["fasta=","fasta_dir=","suffix=","max_iteration=","msa_tool=",
"num_threads=","mode=","gap_penalty", "unique_gap_penalty", "insertion_penalty=", "unique_insertion_penalty=", "mismatch_penalty=",
"match_reward=", "log","help"])
except getopt.GetoptError as err:
print (str(err))
usage()
for o, a in opts:
if o in ("-f", "--fasta"):
fastalist = a.split(",")
statsout = fastalist[0]+".info"
tabout = fastalist[0]+".csv"
finaldir = os.path.dirname(fastalist[0])+"ps_out"
tmpdir = os.path.dirname(fastalist[0])+"ps_tmp"
elif o in ("-h","--help"):
usage()
elif o in ("-n", "--num_threads"):
num_threads = int(a)
elif o in ("-F","--fasta_dir"):
fastadir = a
finaldir = fastadir+os.sep+"ps_out"
tmpdir = fastadir+os.sep+"ps_tmp"
elif o in ("-s", "--suffix"):
suffix = a
elif o in ("-i", "--max_iteration"):
max_iter = int(a)
elif o in ("-a", "--msa_tool"):
msa_tool = a.lower()
elif o in ("-m", "--mode"):
mode = a.lower()
elif o in ("-l", "--log"):
logging = True
#only for mode "custom":
elif o in ("-g", "--gap_penalty"):
gap_penalty = float(a)
elif o in ("-G","--unique_gap_penalty"):
unique_gap_penalty = float(a)
elif o in ("-j", "--insertion_penalty"):
insertion_penalty = float(a)
elif o in ("-J", "--unique_insertion_penalty"):
unique_insertion_penalty = float(a)
elif o in ("-M", "--mismatch_penalty"):
mismatch_penalty = float(a)
elif o in ("-r", "--match_reward"):
match_reward = float(a)
else:
assert False, "unhandled option"
if not fastalist and not (fastadir and suffix):
usage()
else:
checkPath(progname = msa_tool)
checkMode(mode=mode)
finaldir = adjustDir(finaldir, mode)
tmpdir = adjustDir(tmpdir, mode)
global SEMAPHORE
SEMAPHORE=threading.BoundedSemaphore(num_threads)
if not os.path.exists(finaldir):
os.mkdir(finaldir)
if not os.path.exists(tmpdir):
os.mkdir(tmpdir)
if fastadir:
print(suffix)
for f in getFastaList(fastadir, suffix):
print(f)
fastalist.append(f)
for fasta in fastalist:
SchoenifyThread(fasta, max_iter,finaldir,tmpdir, msa_tool, mode, logging, gap_penalty, unique_gap_penalty, insertion_penalty, unique_insertion_penalty, mismatch_penalty , match_reward).start()
#############################################
LOCK = threading.Lock()
SEMAPHORE = threading.BoundedSemaphore()
##########
if __name__ == "__main__":
main()<|fim▁end|> | if not toKeep: |
<|file_name|>script.js<|end_file_name|><|fim▁begin|>if ( !window.console ) window.console = { log:function(){} };
jQuery(document).ready(function($) {
console.log('Keep being awesome.');<|fim▁hole|><|fim▁end|> |
}); |
<|file_name|>stream.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Stream channels
///
/// This is the flavor of channels which are optimized for one sender and one
/// receiver. The sender will be upgraded to a shared channel if the channel is
/// cloned.
///
/// High level implementation details can be found in the comment of the parent
/// module.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::Message::*;
use core::prelude::*;
use core::cmp;
use core::isize;
use thread;
use sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool};
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use sync::mpsc::spsc_queue as spsc;
const DISCONNECTED: isize = isize::MIN;
#[cfg(test)]
const MAX_STEALS: isize = 5;
#[cfg(not(test))]
const MAX_STEALS: isize = 1 << 20;
pub struct Packet<T> {
queue: spsc::Queue<Message<T>>, // internal queue for all message
cnt: AtomicIsize, // How many items are on this channel
steals: int, // How many times has a port received without blocking?
to_wake: AtomicUsize, // SignalToken for the blocked thread to wake up
port_dropped: AtomicBool, // flag if the channel has been destroyed.
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelSuccess,
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
}
// Any message could contain an "upgrade request" to a new shared port, so the
// internal queue it's a queue of T, but rather Message<T>
enum Message<T> {
Data(T),
GoUp(Receiver<T>),
}
impl<T: Send> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
queue: unsafe { spsc::Queue::new(128) },
cnt: AtomicIsize::new(0),
steals: 0,
to_wake: AtomicUsize::new(0),
port_dropped: AtomicBool::new(false),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// If the other port has deterministically gone away, then definitely
// must return the data back up the stack. Otherwise, the data is
// considered as being sent.
if self.port_dropped.load(Ordering::SeqCst) { return Err(t) }
match self.do_send(Data(t)) {
UpSuccess | UpDisconnected => {},
UpWoke(token) => { token.signal(); }
}
Ok(())
}
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
// If the port has gone away, then there's no need to proceed any
// further.
if self.port_dropped.load(Ordering::SeqCst) { return UpDisconnected }
self.do_send(GoUp(up))
}
fn do_send(&mut self, t: Message<T>) -> UpgradeResult {
self.queue.push(t);
match self.cnt.fetch_add(1, Ordering::SeqCst) {
// As described in the mod's doc comment, -1 == wakeup
-1 => UpWoke(self.take_to_wake()),
// As as described before, SPSC queues must be >= -2
-2 => UpSuccess,
// Be sure to preserve the disconnected state, and the return value
// in this case is going to be whether our data was received or not.
// This manifests itself on whether we have an empty queue or not.
//
// Primarily, are required to drain the queue here because the port
// will never remove this data. We can only have at most one item to
// drain (the port drains the rest).
DISCONNECTED => {
self.cnt.store(DISCONNECTED, Ordering::SeqCst);
let first = self.queue.pop();
let second = self.queue.pop();
assert!(second.is_none());
match first {
Some(..) => UpSuccess, // we failed to send the data
None => UpDisconnected, // we successfully sent data
}
}
// Otherwise we just sent some data on a non-waiting queue, so just
// make sure the world is sane and carry on!
n => { assert!(n >= 0); UpSuccess }
}
}
// Consumes ownership of the 'to_wake' field.<|fim▁hole|> let ptr = self.to_wake.load(Ordering::SeqCst);
self.to_wake.store(0, Ordering::SeqCst);
assert!(ptr != 0);
unsafe { SignalToken::cast_from_uint(ptr) }
}
// Decrements the count on the channel for a sleeper, returning the sleeper
// back if it shouldn't sleep. Note that this is the location where we take
// steals into account.
fn decrement(&mut self, token: SignalToken) -> Result<(), SignalToken> {
assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
let ptr = unsafe { token.cast_to_uint() };
self.to_wake.store(ptr, Ordering::SeqCst);
let steals = self.steals;
self.steals = 0;
match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) {
DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); }
// If we factor in our steals and notice that the channel has no
// data, we successfully sleep
n => {
assert!(n >= 0);
if n - steals <= 0 { return Ok(()) }
}
}
self.to_wake.store(0, Ordering::SeqCst);
Err(unsafe { SignalToken::cast_from_uint(ptr) })
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Optimistic preflight check (scheduling is expensive).
match self.try_recv() {
Err(Empty) => {}
data => return data,
}
// Welp, our channel has no data. Deschedule the current task and
// initiate the blocking protocol.
let (wait_token, signal_token) = blocking::tokens();
if self.decrement(signal_token).is_ok() {
wait_token.wait()
}
match self.try_recv() {
// Messages which actually popped from the queue shouldn't count as
// a steal, so offset the decrement here (we already have our
// "steal" factored into the channel count above).
data @ Ok(..) |
data @ Err(Upgraded(..)) => {
self.steals -= 1;
data
}
data => data,
}
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.queue.pop() {
// If we stole some data, record to that effect (this will be
// factored into cnt later on).
//
// Note that we don't allow steals to grow without bound in order to
// prevent eventual overflow of either steals or cnt as an overflow
// would have catastrophic results. Sometimes, steals > cnt, but
// other times cnt > steals, so we don't know the relation between
// steals and cnt. This code path is executed only rarely, so we do
// a pretty slow operation, of swapping 0 into cnt, taking steals
// down as much as possible (without going negative), and then
// adding back in whatever we couldn't factor into steals.
Some(data) => {
if self.steals > MAX_STEALS {
match self.cnt.swap(0, Ordering::SeqCst) {
DISCONNECTED => {
self.cnt.store(DISCONNECTED, Ordering::SeqCst);
}
n => {
let m = cmp::min(n, self.steals);
self.steals -= m;
self.bump(n - m);
}
}
assert!(self.steals >= 0);
}
self.steals += 1;
match data {
Data(t) => Ok(t),
GoUp(up) => Err(Upgraded(up)),
}
}
None => {
match self.cnt.load(Ordering::SeqCst) {
n if n != DISCONNECTED => Err(Empty),
// This is a little bit of a tricky case. We failed to pop
// data above, and then we have viewed that the channel is
// disconnected. In this window more data could have been
// sent on the channel. It doesn't really make sense to
// return that the channel is disconnected when there's
// actually data on it, so be extra sure there's no data by
// popping one more time.
//
// We can ignore steals because the other end is
// disconnected and we'll never need to really factor in our
// steals again.
_ => {
match self.queue.pop() {
Some(Data(t)) => Ok(t),
Some(GoUp(up)) => Err(Upgraded(up)),
None => Err(Disconnected),
}
}
}
}
}
}
pub fn drop_chan(&mut self) {
// Dropping a channel is pretty simple, we just flag it as disconnected
// and then wakeup a blocker if there is one.
match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) {
-1 => { self.take_to_wake().signal(); }
DISCONNECTED => {}
n => { assert!(n >= 0); }
}
}
pub fn drop_port(&mut self) {
// Dropping a port seems like a fairly trivial thing. In theory all we
// need to do is flag that we're disconnected and then everything else
// can take over (we don't have anyone to wake up).
//
// The catch for Ports is that we want to drop the entire contents of
// the queue. There are multiple reasons for having this property, the
// largest of which is that if another chan is waiting in this channel
// (but not received yet), then waiting on that port will cause a
// deadlock.
//
// So if we accept that we must now destroy the entire contents of the
// queue, this code may make a bit more sense. The tricky part is that
// we can't let any in-flight sends go un-dropped, we have to make sure
// *everything* is dropped and nothing new will come onto the channel.
// The first thing we do is set a flag saying that we're done for. All
// sends are gated on this flag, so we're immediately guaranteed that
// there are a bounded number of active sends that we'll have to deal
// with.
self.port_dropped.store(true, Ordering::SeqCst);
// Now that we're guaranteed to deal with a bounded number of senders,
// we need to drain the queue. This draining process happens atomically
// with respect to the "count" of the channel. If the count is nonzero
// (with steals taken into account), then there must be data on the
// channel. In this case we drain everything and then try again. We will
// continue to fail while active senders send data while we're dropping
// data, but eventually we're guaranteed to break out of this loop
// (because there is a bounded number of senders).
let mut steals = self.steals;
while {
let cnt = self.cnt.compare_and_swap(
steals, DISCONNECTED, Ordering::SeqCst);
cnt != DISCONNECTED && cnt != steals
} {
loop {
match self.queue.pop() {
Some(..) => { steals += 1; }
None => break
}
}
}
// At this point in time, we have gated all future senders from sending,
// and we have flagged the channel as being disconnected. The senders
// still have some responsibility, however, because some sends may not
// complete until after we flag the disconnection. There are more
// details in the sending methods that see DISCONNECTED
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// Tests to see whether this port can receive without blocking. If Ok is
// returned, then that's the answer. If Err is returned, then the returned
// port needs to be queried instead (an upgrade happened)
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
// We peek at the queue to see if there's anything on it, and we use
// this return value to determine if we should pop from the queue and
// upgrade this channel immediately. If it looks like we've got an
// upgrade pending, then go through the whole recv rigamarole to update
// the internal state.
match self.queue.peek() {
Some(&mut GoUp(..)) => {
match self.recv() {
Err(Upgraded(port)) => Err(port),
_ => unreachable!(),
}
}
Some(..) => Ok(true),
None => Ok(false)
}
}
// increment the count on the channel (used for selection)
fn bump(&mut self, amt: int) -> int {
match self.cnt.fetch_add(amt, Ordering::SeqCst) {
DISCONNECTED => {
self.cnt.store(DISCONNECTED, Ordering::SeqCst);
DISCONNECTED
}
n => n
}
}
// Attempts to start selecting on this port. Like a oneshot, this can fail
// immediately because of an upgrade.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
match self.decrement(token) {
Ok(()) => SelSuccess,
Err(token) => {
let ret = match self.queue.peek() {
Some(&mut GoUp(..)) => {
match self.queue.pop() {
Some(GoUp(port)) => SelUpgraded(token, port),
_ => unreachable!(),
}
}
Some(..) => SelCanceled,
None => SelCanceled,
};
// Undo our decrement above, and we should be guaranteed that the
// previous value is positive because we're not going to sleep
let prev = self.bump(1);
assert!(prev == DISCONNECTED || prev >= 0);
return ret;
}
}
}
// Removes a previous task from being blocked in this port
pub fn abort_selection(&mut self,
was_upgrade: bool) -> Result<bool, Receiver<T>> {
// If we're aborting selection after upgrading from a oneshot, then
// we're guarantee that no one is waiting. The only way that we could
// have seen the upgrade is if data was actually sent on the channel
// half again. For us, this means that there is guaranteed to be data on
// this channel. Furthermore, we're guaranteed that there was no
// start_selection previously, so there's no need to modify `self.cnt`
// at all.
//
// Hence, because of these invariants, we immediately return `Ok(true)`.
// Note that the data may not actually be sent on the channel just yet.
// The other end could have flagged the upgrade but not sent data to
// this end. This is fine because we know it's a small bounded windows
// of time until the data is actually sent.
if was_upgrade {
assert_eq!(self.steals, 0);
assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
return Ok(true)
}
// We want to make sure that the count on the channel goes non-negative,
// and in the stream case we can have at most one steal, so just assume
// that we had one steal.
let steals = 1;
let prev = self.bump(steals + 1);
// If we were previously disconnected, then we know for sure that there
// is no task in to_wake, so just keep going
let has_data = if prev == DISCONNECTED {
assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
true // there is data, that data is that we're disconnected
} else {
let cur = prev + steals + 1;
assert!(cur >= 0);
// If the previous count was negative, then we just made things go
// positive, hence we passed the -1 boundary and we're responsible
// for removing the to_wake() field and trashing it.
//
// If the previous count was positive then we're in a tougher
// situation. A possible race is that a sender just incremented
// through -1 (meaning it's going to try to wake a task up), but it
// hasn't yet read the to_wake. In order to prevent a future recv()
// from waking up too early (this sender picking up the plastered
// over to_wake), we spin loop here waiting for to_wake to be 0.
// Note that this entire select() implementation needs an overhaul,
// and this is *not* the worst part of it, so this is not done as a
// final solution but rather out of necessity for now to get
// something working.
if prev < 0 {
drop(self.take_to_wake());
} else {
while self.to_wake.load(Ordering::SeqCst) != 0 {
thread::yield_now();
}
}
assert_eq!(self.steals, 0);
self.steals = steals;
// if we were previously positive, then there's surely data to
// receive
prev >= 0
};
// Now that we've determined that this queue "has data", we peek at the
// queue to see if the data is an upgrade or not. If it's an upgrade,
// then we need to destroy this port and abort selection on the
// upgraded port.
if has_data {
match self.queue.peek() {
Some(&mut GoUp(..)) => {
match self.queue.pop() {
Some(GoUp(port)) => Err(port),
_ => unreachable!(),
}
}
_ => Ok(true),
}
} else {
Ok(false)
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
// Note that this load is not only an assert for correctness about
// disconnection, but also a proper fence before the read of
// `to_wake`, so this assert cannot be removed with also removing
// the `to_wake` assert.
assert_eq!(self.cnt.load(Ordering::SeqCst), DISCONNECTED);
assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
}
}<|fim▁end|> | fn take_to_wake(&mut self) -> SignalToken { |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from .models import RegistrationProfile
from opps.core.admin import apply_opps_rules
@apply_opps_rules('registration')
class RegistrationAdmin(admin.ModelAdmin):
actions = ['activate_users', 'resend_activation_email']
list_display = ('user', 'activation_key_expired', 'activation_key')
raw_id_fields = ['user']<|fim▁hole|> Activates the selected users, if they are not alrady
activated.
"""
for profile in queryset:
RegistrationProfile.objects.activate_user(profile.activation_key)
activate_users.short_description = _("Activate users")
def resend_activation_email(self, request, queryset):
"""
Re-sends activation emails for the selected users.
Note that this will *only* send activation emails for users
who are eligible to activate; emails will not be sent to users
whose activation keys have expired or who have already
activated.
"""
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
for profile in queryset:
if not profile.activation_key_expired():
profile.send_activation_email(site)
resend_activation_email.short_description = _("Re-send activation emails")
admin.site.register(RegistrationProfile, RegistrationAdmin)<|fim▁end|> | search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email')
def activate_users(self, request, queryset):
""" |
<|file_name|>sets.js<|end_file_name|><|fim▁begin|>'use strict';
/*global require, after, before*/
var async = require('async'),
assert = require('assert'),
db = require('../mocks/databasemock');
describe('Set methods', function() {
describe('setAdd()', function() {
it('should add to a set', function(done) {
db.setAdd('testSet1', 5, function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
done();
});
});
it('should add an array to a set', function(done) {
db.setAdd('testSet1', [1, 2, 3, 4], function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
done();
});
});
});
describe('getSetMembers()', function() {
before(function(done) {
db.setAdd('testSet2', [1,2,3,4,5], done);
});
it('should return an empty set', function(done) {
db.getSetMembers('doesnotexist', function(err, set) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(set), true);
assert.equal(set.length, 0);
done();
});
});
it('should return a set with all elements', function(done) {
db.getSetMembers('testSet2', function(err, set) {
assert.equal(err, null);
assert.equal(set.length, 5);
set.forEach(function(value) {
assert.notEqual(['1', '2', '3', '4', '5'].indexOf(value), -1);
});
done();
});
});
});
describe('setsAdd()', function() {
it('should add to multiple sets', function(done) {
db.setsAdd(['set1', 'set2'], 'value', function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
done();
});
});
});
describe('getSetsMembers()', function() {
before(function(done) {
db.setsAdd(['set3', 'set4'], 'value', done);
});
it('should return members of two sets', function(done) {
db.getSetsMembers(['set3', 'set4'], function(err, sets) {
assert.equal(err, null);
assert.equal(Array.isArray(sets), true);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(sets[0]) && Array.isArray(sets[1]), true);
assert.strictEqual(sets[0][0], 'value');
assert.strictEqual(sets[1][0], 'value');
done();
});
});
});
describe('isSetMember()', function() {
before(function(done) {
db.setAdd('testSet3', 5, done);
});
it('should return false if element is not member of set', function(done) {
db.isSetMember('testSet3', 10, function(err, isMember) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(isMember, false);
done();
});
});
it('should return true if element is a member of set', function(done) {
db.isSetMember('testSet3', 5, function(err, isMember) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(isMember, true);
done();
});
});
});
describe('isSetMembers()', function() {
before(function(done) {
db.setAdd('testSet4', [1, 2, 3, 4, 5], done);
});
it('should return an array of booleans', function(done) {
db.isSetMembers('testSet4', ['1', '2', '10', '3'], function(err, members) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(members), true);
assert.deepEqual(members, [true, true, false, true]);
done();
});
});
});
describe('isMemberOfSets()', function() {
before(function(done) {
db.setsAdd(['set1', 'set2'], 'value', done);
});
it('should return an array of booleans', function(done) {
db.isMemberOfSets(['set1', 'testSet1', 'set2', 'doesnotexist'], 'value', function(err, members) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(members), true);
assert.deepEqual(members, [true, false, true, false]);
done();
});
});
});
describe('setCount()', function() {
before(function(done) {
db.setAdd('testSet5', [1,2,3,4,5], done);
});
it('should return the element count of set', function(done) {
db.setCount('testSet5', function(err, count) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.strictEqual(count, 5);
done();
});
});
});
describe('setsCount()', function() {
before(function(done) {
async.parallel([
async.apply(db.setAdd, 'set5', [1,2,3,4,5]),
async.apply(db.setAdd, 'set6', 1),
async.apply(db.setAdd, 'set7', 2)
], done);
});
it('should return the element count of sets', function(done) {
db.setsCount(['set5', 'set6', 'set7', 'doesnotexist'], function(err, counts) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(counts), true);
assert.deepEqual(counts, [5, 1, 1, 0]);
done();
});
});
});
describe('setRemove()', function() {
before(function(done) {
db.setAdd('testSet6', [1, 2], done);
});
it('should remove a element from set', function(done) {
db.setRemove('testSet6', '2', function(err) {<|fim▁hole|>
db.isSetMember('testSet6', '2', function(err, isMember) {
assert.equal(err, null);
assert.equal(isMember, false);
done();
});
});
});
});
describe('setsRemove()', function() {
before(function(done) {
db.setsAdd(['set1', 'set2'], 'value', done);
});
it('should remove a element from multiple sets', function(done) {
db.setsRemove(['set1', 'set2'], 'value', function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
db.isMemberOfSets(['set1', 'set2'], 'value', function(err, members) {
assert.equal(err, null);
assert.deepEqual(members, [false, false]);
done();
});
});
});
});
describe('setRemoveRandom()', function() {
before(function(done) {
db.setAdd('testSet7', [1,2,3,4,5], done);
});
it('should remove a random element from set', function(done) {
db.setRemoveRandom('testSet7', function(err, element) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
db.isSetMember('testSet', element, function(err, ismember) {
assert.equal(err, null);
assert.equal(ismember, false);
done();
});
});
});
});
after(function(done) {
db.flushdb(done);
});
});<|fim▁end|> | assert.equal(err, null);
assert.equal(arguments.length, 1); |
<|file_name|>base_repo.py<|end_file_name|><|fim▁begin|># Copyright 2015 FUJITSU LIMITED
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
class BaseRepo(object):
def __init__(self, config):
self._find_alarm_action_sql = \
"""SELECT id, type, name, address, period
FROM alarm_action as aa
JOIN notification_method as nm ON aa.action_id = nm.id<|fim▁hole|> WHERE alarm.id = %s"""
self._insert_notification_types_sql = \
"""INSERT INTO notification_method_type (name) VALUES ( %s)"""
self._find_all_notification_types_sql = """SELECT name from notification_method_type """
self._get_notification_sql = """SELECT name, type, address, period
FROM notification_method
WHERE id = %s"""<|fim▁end|> | WHERE aa.alarm_definition_id = %s and aa.alarm_state = %s"""
self._find_alarm_state_sql = \
"""SELECT state
FROM alarm |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import json
from idpproxy.social.oauth import OAuth
import oauth2 as oauth
#from xml.etree import ElementTree as ET
import logging
logger = logging.getLogger(__name__)
__author__ = 'rohe0002'
class LinkedIn(OAuth):
def __init__(self, client_id, client_secret, **kwargs):
OAuth.__init__(self, client_id, client_secret, **kwargs)
def get_profile(self, info_set):
token = oauth.Token(key=info_set["oauth_token"][0],
secret=info_set["oauth_token_secret"][0])
client = oauth.Client(self.consumer, token)
resp, content = client.request(self.extra["userinfo_endpoint"], "GET")
# # content in XML :-(
# logger.debug("UserInfo XML: %s" % content)
# res = {}
# root = ET.fromstring(content)
# for child in root:
# res[child.tag] = child.text
res = json.loads(content)<|fim▁hole|> return resp, res<|fim▁end|> | logger.debug("userinfo: %s" % res)
res["user_id"] = info_set["oauth_token"] |
<|file_name|>CGDeclCXX.cpp<|end_file_name|><|fim▁begin|>//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with code generation of C++ declarations
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
#include "CGCXXABI.h"
#include "CGObjCRuntime.h"
#include "CGOpenMPRuntime.h"
#include "clang/Basic/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/Path.h"
using namespace clang;
using namespace CodeGen;
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
ConstantAddress DeclPtr) {
assert(
(D.hasGlobalStorage() ||
(D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
"VarDecl must have global or local (in the case of OpenCL) storage!");
assert(!D.getType()->isReferenceType() &&
"Should not call EmitDeclInit on a reference!");
QualType type = D.getType();
LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
const Expr *Init = D.getInit();
switch (CGF.getEvaluationKind(type)) {
case TEK_Scalar: {
CodeGenModule &CGM = CGF.CGM;
if (lv.isObjCStrong())
CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
DeclPtr, D.getTLSKind());
else if (lv.isObjCWeak())
CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
DeclPtr);
else
CGF.EmitScalarInit(Init, &D, lv, false);
return;
}
case TEK_Complex:
CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
return;
case TEK_Aggregate:
CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased,
AggValueSlot::DoesNotOverlap));
return;
}
llvm_unreachable("bad evaluation kind");
}
/// Emit code to cause the destruction of the given variable with
/// static storage duration.
static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
ConstantAddress Addr) {
// Honor __attribute__((no_destroy)) and bail instead of attempting
// to emit a reference to a possibly nonexistent destructor, which
// in turn can cause a crash. This will result in a global constructor
// that isn't balanced out by a destructor call as intended by the
// attribute. This also checks for -fno-c++-static-destructors and
// bails even if the attribute is not present.
if (D.isNoDestroy(CGF.getContext()))
return;
CodeGenModule &CGM = CGF.CGM;
// FIXME: __attribute__((cleanup)) ?
QualType Type = D.getType();
QualType::DestructionKind DtorKind = Type.isDestructedType();
switch (DtorKind) {
case QualType::DK_none:
return;
case QualType::DK_cxx_destructor:
break;
case QualType::DK_objc_strong_lifetime:
case QualType::DK_objc_weak_lifetime:
case QualType::DK_nontrivial_c_struct:
// We don't care about releasing objects during process teardown.
assert(!D.getTLSKind() && "should have rejected this");
return;
}
llvm::FunctionCallee Func;
llvm::Constant *Argument;
// Special-case non-array C++ destructors, if they have the right signature.
// Under some ABIs, destructors return this instead of void, and cannot be
// passed directly to __cxa_atexit if the target does not allow this
// mismatch.
const CXXRecordDecl *Record = Type->getAsCXXRecordDecl();
bool CanRegisterDestructor =
Record && (!CGM.getCXXABI().HasThisReturn(
GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
CGM.getCXXABI().canCallMismatchedFunctionType());
// If __cxa_atexit is disabled via a flag, a different helper function is
// generated elsewhere which uses atexit instead, and it takes the destructor
// directly.
bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
if (Record && (CanRegisterDestructor || UsingExternalHelper)) {
assert(!Record->hasTrivialDestructor());
CXXDestructorDecl *Dtor = Record->getDestructor();
Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete));
Argument = llvm::ConstantExpr::getBitCast(
Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo());
// Otherwise, the standard logic requires a helper function.
} else {
Func = CodeGenFunction(CGM)
.generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind),
CGF.needsEHCleanup(DtorKind), &D);
Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
}
CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
}
/// Emit code to cause the variable at the given address to be considered as
/// constant from this point onwards.
static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
llvm::Constant *Addr) {
return CGF.EmitInvariantStart(
Addr, CGF.getContext().getTypeSizeInChars(D.getType()));
}
void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) {
// Do not emit the intrinsic if we're not optimizing.
if (!CGM.getCodeGenOpts().OptimizationLevel)
return;
// Grab the llvm.invariant.start intrinsic.
llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
// Overloaded address space type.
llvm::Type *ObjectPtr[1] = {Int8PtrTy};
llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr);
// Emit a call with the size in bytes of the object.
uint64_t Width = Size.getQuantity();
llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(Int64Ty, Width),
llvm::ConstantExpr::getBitCast(Addr, Int8PtrTy)};
Builder.CreateCall(InvariantStart, Args);
}
void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
llvm::Constant *DeclPtr,
bool PerformInit) {
const Expr *Init = D.getInit();
QualType T = D.getType();
// The address space of a static local variable (DeclPtr) may be different
// from the address space of the "this" argument of the constructor. In that
// case, we need an addrspacecast before calling the constructor.
//
// struct StructWithCtor {
// __device__ StructWithCtor() {...}
// };
// __device__ void foo() {
// __shared__ StructWithCtor s;
// ...
// }
//
// For example, in the above CUDA code, the static local variable s has a
// "shared" address space qualifier, but the constructor of StructWithCtor
// expects "this" in the "generic" address space.
unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
if (ActualAddrSpace != ExpectedAddrSpace) {
llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T);
llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
}
ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D));
if (!T->isReferenceType()) {
if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
D.hasAttr<OMPThreadPrivateDeclAttr>()) {
(void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
&D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
PerformInit, this);
}
if (PerformInit)
EmitDeclInit(*this, D, DeclAddr);
if (CGM.isTypeConstant(D.getType(), true))
EmitDeclInvariant(*this, D, DeclPtr);
else
EmitDeclDestroy(*this, D, DeclAddr);
return;
}
assert(PerformInit && "cannot have constant initializer which needs "
"destruction for reference");
RValue RV = EmitReferenceBindingToExpr(Init);
EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
}
/// Create a stub function, suitable for being passed to atexit,
/// which passes the given address to the given destructor function.
llvm::Function *CodeGenFunction::createAtExitStub(const VarDecl &VD,
llvm::FunctionCallee dtor,
llvm::Constant *addr) {
// Get the destructor function type, void(*)(void).
llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
SmallString<256> FnName;
{
llvm::raw_svector_ostream Out(FnName);
CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
}
const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
ty, FnName.str(), FI, VD.getLocation());
CodeGenFunction CGF(CGM);
CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit),
CGM.getContext().VoidTy, fn, FI, FunctionArgList());
llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
// Make sure the call and the callee agree on calling convention.
if (llvm::Function *dtorFn =
dyn_cast<llvm::Function>(dtor.getCallee()->stripPointerCasts()))
call->setCallingConv(dtorFn->getCallingConv());
CGF.FinishFunction();
return fn;
}
/// Register a global destructor using the C atexit runtime function.
void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
llvm::FunctionCallee dtor,
llvm::Constant *addr) {
// Create a function which calls the destructor.
llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
registerGlobalDtorWithAtExit(dtorStub);
}
void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
// extern "C" int atexit(void (*f)(void));
llvm::FunctionType *atexitTy =
llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
llvm::FunctionCallee atexit =
CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
/*Local=*/true);
if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
atexitFn->setDoesNotThrow();
EmitNounwindRuntimeCall(atexit, dtorStub);
}
void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
llvm::GlobalVariable *DeclPtr,
bool PerformInit) {
// If we've been asked to forbid guard variables, emit an error now.
// This diagnostic is hard-coded for Darwin's use case; we can find
// better phrasing if someone else needs it.
if (CGM.getCodeGenOpts().ForbidGuardVariables)
CGM.Error(D.getLocation(),
"this initialization requires a guard variable, which "
"the kernel does not support");
CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
}
void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
llvm::BasicBlock *InitBlock,
llvm::BasicBlock *NoInitBlock,
GuardKind Kind,
const VarDecl *D) {
assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
// A guess at how many times we will enter the initialization of a
// variable, depending on the kind of variable.
static const uint64_t InitsPerTLSVar = 1024;
static const uint64_t InitsPerLocalVar = 1024 * 1024;
llvm::MDNode *Weights;
if (Kind == GuardKind::VariableGuard && !D->isLocalVarDecl()) {
// For non-local variables, don't apply any weighting for now. Due to our
// use of COMDATs, we expect there to be at most one initialization of the
// variable per DSO, but we have no way to know how many DSOs will try to
// initialize the variable.
Weights = nullptr;
} else {
uint64_t NumInits;
// FIXME: For the TLS case, collect and use profiling information to
// determine a more accurate brach weight.
if (Kind == GuardKind::TlsGuard || D->getTLSKind())
NumInits = InitsPerTLSVar;
else
NumInits = InitsPerLocalVar;
// The probability of us entering the initializer is
// 1 / (total number of times we attempt to initialize the variable).
llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Weights = MDHelper.createBranchWeights(1, NumInits - 1);
}
Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
}
llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
SourceLocation Loc, bool TLS) {
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Name, &getModule());
if (!getLangOpts().AppleKext && !TLS) {
// Set the section if needed.
if (const char *Section = getTarget().getStaticInitSectionSpecifier())
Fn->setSection(Section);
}
SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Fn->setCallingConv(getRuntimeCC());
if (!getLangOpts().Exceptions)
Fn->setDoesNotThrow();
if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
!isInSanitizerBlacklist(SanitizerKind::Address, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
!isInSanitizerBlacklist(SanitizerKind::KernelAddress, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
!isInSanitizerBlacklist(SanitizerKind::HWAddress, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
!isInSanitizerBlacklist(SanitizerKind::KernelHWAddress, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
!isInSanitizerBlacklist(SanitizerKind::Thread, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeThread);
if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
!isInSanitizerBlacklist(SanitizerKind::Memory, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
!isInSanitizerBlacklist(SanitizerKind::KernelMemory, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
!isInSanitizerBlacklist(SanitizerKind::SafeStack, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SafeStack);
if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
!isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
auto RASignKind = getCodeGenOpts().getSignReturnAddress();
if (RASignKind != CodeGenOptions::SignReturnAddressScope::None) {
Fn->addFnAttr("sign-return-address",
RASignKind == CodeGenOptions::SignReturnAddressScope::All
? "all"
: "non-leaf");
auto RASignKey = getCodeGenOpts().getSignReturnAddressKey();
Fn->addFnAttr("sign-return-address-key",
RASignKey == CodeGenOptions::SignReturnAddressKeyValue::AKey
? "a_key"
: "b_key");
}
if (getCodeGenOpts().BranchTargetEnforcement)
Fn->addFnAttr("branch-target-enforcement");
return Fn;
}
/// Create a global pointer to a function that will initialize a global
/// variable. The user has requested that this pointer be emitted in a specific
/// section.
void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
llvm::GlobalVariable *GV,
llvm::Function *InitFunc,
InitSegAttr *ISA) {
llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
TheModule, InitFunc->getType(), /*isConstant=*/true,
llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
PtrArray->setSection(ISA->getSection());
addUsedGlobal(PtrArray);
// If the GV is already in a comdat group, then we have to join it.
if (llvm::Comdat *C = GV->getComdat())
PtrArray->setComdat(C);
}
void
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
llvm::GlobalVariable *Addr,
bool PerformInit) {
// According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
// __constant__ and __shared__ variables defined in namespace scope,
// that are of class type, cannot have a non-empty constructor. All
// the checks have been done in Sema by now. Whatever initializers
// are allowed are empty and we just need to ignore them here.
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
(D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
D->hasAttr<CUDASharedAttr>()))
return;
if (getLangOpts().OpenMP &&
getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit))
return;
// Check if we've already initialized this decl.
auto I = DelayedCXXInitPosition.find(D);
if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
return;
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
SmallString<256> FnName;
{
llvm::raw_svector_ostream Out(FnName);
getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
}
// Create a variable initialization function.
llvm::Function *Fn =
CreateGlobalInitOrDestructFunction(FTy, FnName.str(),
getTypes().arrangeNullaryFunction(),
D->getLocation());
auto *ISA = D->getAttr<InitSegAttr>();
CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
PerformInit);
llvm::GlobalVariable *COMDATKey =
supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
if (D->getTLSKind()) {
// FIXME: Should we support init_priority for thread_local?
// FIXME: We only need to register one __cxa_thread_atexit function for the
// entire TU.
CXXThreadLocalInits.push_back(Fn);
CXXThreadLocalInitVars.push_back(D);
} else if (PerformInit && ISA) {
EmitPointerToInitFunc(D, Addr, Fn, ISA);
} else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
} else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) ||
getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR) {
// C++ [basic.start.init]p2:
// Definitions of explicitly specialized class template static data
// members have ordered initialization. Other class template static data
// members (i.e., implicitly or explicitly instantiated specializations)
// have unordered initialization.
//
// As a consequence, we can put them into their own llvm.global_ctors entry.
//
// If the global is externally visible, put the initializer into a COMDAT
// group with the global being initialized. On most platforms, this is a
// minor startup time optimization. In the MS C++ ABI, there are no guard
// variables, so this COMDAT key is required for correctness.
AddGlobalCtor(Fn, 65535, COMDATKey);
if (getTarget().getCXXABI().isMicrosoft() && COMDATKey) {
// In The MS C++, MS add template static data member in the linker
// drective.
addUsedGlobal(COMDATKey);
}
} else if (D->hasAttr<SelectAnyAttr>()) {
// SelectAny globals will be comdat-folded. Put the initializer into a
// COMDAT group associated with the global, so the initializers get folded
// too.
AddGlobalCtor(Fn, 65535, COMDATKey);
} else {
I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
if (I == DelayedCXXInitPosition.end()) {
CXXGlobalInits.push_back(Fn);
} else if (I->second != ~0U) {
assert(I->second < CXXGlobalInits.size() &&
CXXGlobalInits[I->second] == nullptr);
CXXGlobalInits[I->second] = Fn;
}
}
// Remember that we already emitted the initializer for this global.
DelayedCXXInitPosition[D] = ~0U;
}
void CodeGenModule::EmitCXXThreadLocalInitFunc() {
getCXXABI().EmitThreadLocalInitFuncs(
*this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
CXXThreadLocalInits.clear();
CXXThreadLocalInitVars.clear();
CXXThreadLocals.clear();
}
void
CodeGenModule::EmitCXXGlobalInitFunc() {
while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
CXXGlobalInits.pop_back();
if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
return;
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
// Create our global initialization function.
if (!PrioritizedCXXGlobalInits.empty()) {
SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
PrioritizedCXXGlobalInits.end());
// Iterate over "chunks" of ctors with same priority and emit each chunk
// into separate function. Note - everything is sorted first by priority,
// second - by lex order, so we emit ctor functions in proper order.
for (SmallVectorImpl<GlobalInitData >::iterator
I = PrioritizedCXXGlobalInits.begin(),
E = PrioritizedCXXGlobalInits.end(); I != E; ) {
SmallVectorImpl<GlobalInitData >::iterator
PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
LocalCXXGlobalInits.clear();
unsigned Priority = I->first.priority;
// Compute the function suffix from priority. Prepend with zeroes to make
// sure the function names are also ordered as priorities.
std::string PrioritySuffix = llvm::utostr(Priority);
// Priority is always <= 65535 (enforced by sema).
PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
FTy, "_GLOBAL__I_" + PrioritySuffix, FI);
for (; I < PrioE; ++I)
LocalCXXGlobalInits.push_back(I->second);
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
AddGlobalCtor(Fn, Priority);
}
PrioritizedCXXGlobalInits.clear();
}
// Include the filename in the symbol name. Including "sub_" matches gcc and
// makes sure these symbols appear lexicographically behind the symbols with
// priority emitted above.
SmallString<128> FileName = llvm::sys::path::filename(getModule().getName());
if (FileName.empty())
FileName = "<null>";
for (size_t i = 0; i < FileName.size(); ++i) {
// Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
// to be the set of C preprocessing numbers.
if (!isPreprocessingNumberBody(FileName[i]))
FileName[i] = '_';
}
llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
FTy, llvm::Twine("_GLOBAL__sub_I_", FileName), FI);
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
AddGlobalCtor(Fn);
// In OpenCL global init functions must be converted to kernels in order to
// be able to launch them from the host.
// FIXME: Some more work might be needed to handle destructors correctly.
// Current initialization function makes use of function pointers callbacks.
// We can't support function pointers especially between host and device.
// However it seems global destruction has little meaning without any
// dynamic resource allocation on the device and program scope variables are
// destroyed by the runtime when program is released.
if (getLangOpts().OpenCL) {
GenOpenCLArgMetadata(Fn);
Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
}
CXXGlobalInits.clear();
}
void CodeGenModule::EmitCXXGlobalDtorFunc() {
if (CXXGlobalDtors.empty())
return;
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
// Create our global destructor function.
const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
llvm::Function *Fn =
CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a", FI);
CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
AddGlobalDtor(Fn);
}
/// Emit the code necessary to initialize the given global variable.
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
const VarDecl *D,
llvm::GlobalVariable *Addr,
bool PerformInit) {
// Check if we need to emit debug info for variable initializer.
if (D->hasAttr<NoDebugAttr>())
DebugInfo = nullptr; // disable debug info indefinitely for this function
CurEHLocation = D->getBeginLoc();
StartFunction(GlobalDecl(D, DynamicInitKind::Initializer),
getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
FunctionArgList(), D->getLocation(),
D->getInit()->getExprLoc());
// Use guarded initialization if the global variable is weak. This
// occurs for, e.g., instantiated static data members and
// definitions explicitly marked weak.
//
// Also use guarded initialization for a variable with dynamic TLS and
// unordered initialization. (If the initialization is ordered, the ABI
// layer will guard the whole-TU initialization for us.)
if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage() ||
(D->getTLSKind() == VarDecl::TLS_Dynamic &&
isTemplateInstantiation(D->getTemplateSpecializationKind()))) {
EmitCXXGuardedInit(*D, Addr, PerformInit);
} else {
EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
}
FinishFunction();
}
void
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
ArrayRef<llvm::Function *> Decls,
ConstantAddress Guard) {
{
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
getTypes().arrangeNullaryFunction(), FunctionArgList());
// Emit an artificial location for this function.
auto AL = ApplyDebugLocation::CreateArtificial(*this);
llvm::BasicBlock *ExitBlock = nullptr;
if (Guard.isValid()) {
// If we have a guard variable, check whether we've already performed
// these initializations. This happens for TLS initialization functions.
llvm::Value *GuardVal = Builder.CreateLoad(Guard);
llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
"guard.uninitialized");
llvm::BasicBlock *InitBlock = createBasicBlock("init");
ExitBlock = createBasicBlock("exit");
EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
GuardKind::TlsGuard, nullptr);
EmitBlock(InitBlock);
// Mark as initialized before initializing anything else. If the
// initializers use previously-initialized thread_local vars, that's
// probably supposed to be OK, but the standard doesn't say.
Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
// The guard variable can't ever change again.
EmitInvariantStart(
Guard.getPointer(),
CharUnits::fromQuantity(
CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
}
RunCleanupsScope Scope(*this);
// When building in Objective-C++ ARC mode, create an autorelease pool
// around the global initializers.
if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
llvm::Value *token = EmitObjCAutoreleasePoolPush();
EmitObjCAutoreleasePoolCleanup(token);
}
for (unsigned i = 0, e = Decls.size(); i != e; ++i)
if (Decls[i])
EmitRuntimeCall(Decls[i]);
Scope.ForceCleanup();
if (ExitBlock) {
Builder.CreateBr(ExitBlock);
EmitBlock(ExitBlock);
}
}
FinishFunction();
}
void CodeGenFunction::GenerateCXXGlobalDtorsFunc(
llvm::Function *Fn,
const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
llvm::Constant *>> &DtorsAndObjects) {
{
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
getTypes().arrangeNullaryFunction(), FunctionArgList());
// Emit an artificial location for this function.
auto AL = ApplyDebugLocation::CreateArtificial(*this);
// Emit the dtors, in reverse order from construction.
for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
llvm::FunctionType *CalleeTy;
llvm::Value *Callee;
llvm::Constant *Arg;
std::tie(CalleeTy, Callee, Arg) = DtorsAndObjects[e - i - 1];
llvm::CallInst *CI = Builder.CreateCall(CalleeTy, Callee, Arg);
// Make sure the call and the callee agree on calling convention.
if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
CI->setCallingConv(F->getCallingConv());
}
}
FinishFunction();
}
/// generateDestroyHelper - Generates a helper function which, when
/// invoked, destroys the given object. The address of the object
/// should be in global memory.
llvm::Function *CodeGenFunction::generateDestroyHelper(
Address addr, QualType type, Destroyer *destroyer,
bool useEHCleanupForArray, const VarDecl *VD) {
FunctionArgList args;
ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy,
ImplicitParamDecl::Other);
args.push_back(&Dst);<|fim▁hole|> CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
CurEHLocation = VD->getBeginLoc();
StartFunction(VD, getContext().VoidTy, fn, FI, args);
emitDestroy(addr, type, destroyer, useEHCleanupForArray);
FinishFunction();
return fn;
}<|fim▁end|> |
const CGFunctionInfo &FI = |
<|file_name|>complex.rs<|end_file_name|><|fim▁begin|>// Implements http://rosettacode.org/wiki/Arithmetic/Complex
// not_tested
extern crate num;
use num::complex::Complex;
fn main() {
let a = Complex::new(-4.0f32, 5.0);
let b = Complex::new(1.0f32, 1.0);
println!("a = {}", a);
println!("b = {}", b);
println!("a + b = {}", a + b);
println!("a * b = {}", a * b);<|fim▁hole|> println!("1 / a = {}", Complex::new(1.0f32, 0.0) / a);
println!("-a = {}", -a);
println!("conj a = {}", a.conj());
}<|fim▁end|> | |
<|file_name|>ProjectExplorerContentProvider.java<|end_file_name|><|fim▁begin|>/**
* Aptana Studio
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ide.ui.io.navigator;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.Viewer;
import com.aptana.core.util.ArrayUtil;
import com.aptana.ide.core.io.CoreIOPlugin;
import com.aptana.ui.util.UIUtils;
public class ProjectExplorerContentProvider extends FileTreeContentProvider
{
private static final String LOCAL_SHORTCUTS_ID = "com.aptana.ide.core.io.localShortcuts"; //$NON-NLS-1$
private Viewer treeViewer;
private IResourceChangeListener resourceListener = new IResourceChangeListener()
{
public void resourceChanged(IResourceChangeEvent event)
{
// to fix https://jira.appcelerator.org/browse/TISTUD-1695, we need to force a selection update when a
// project is closed or opened
if (shouldUpdateActions(event.getDelta()))
{
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
treeViewer.setSelection(treeViewer.getSelection());
}
});
}
}
};
public ProjectExplorerContentProvider()
{
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE);
}
@Override
public void dispose()
{
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener);
super.dispose();
}
@Override
public Object[] getChildren(Object parentElement)
{
if (parentElement instanceof IResource)
{
return ArrayUtil.NO_OBJECTS;
}
return super.getChildren(parentElement);
}
@Override
public Object[] getElements(Object inputElement)
{
if (inputElement instanceof IWorkspaceRoot)
{
List<Object> children = new ArrayList<Object>();
children.add(LocalFileSystems.getInstance());
children.add(CoreIOPlugin.getConnectionPointManager().getConnectionPointCategory(LOCAL_SHORTCUTS_ID));
return children.toArray(new Object[children.size()]);
}
return super.getElements(inputElement);
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
treeViewer = viewer;
super.inputChanged(viewer, oldInput, newInput);<|fim▁hole|> {
if (delta.getFlags() == IResourceDelta.OPEN)
{
return true;
}
IResourceDelta[] children = delta.getAffectedChildren();
for (IResourceDelta child : children)
{
if (shouldUpdateActions(child))
{
return true;
}
}
return false;
}
}<|fim▁end|> | }
private boolean shouldUpdateActions(IResourceDelta delta) |
<|file_name|>chunk_sparse_matrix_14.cc<|end_file_name|><|fim▁begin|>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// set a few elements in a chunk sparse matrix and test for iterator
// inequality
#include "../tests.h"
#include <deal.II/lac/chunk_sparse_matrix.h>
#include <fstream>
#include <iomanip>
void test (const unsigned int chunk_size)
{
deallog << "Chunk size = " << chunk_size << std::endl;
ChunkSparsityPattern sp (5,5,3,chunk_size);
for (unsigned int i=0; i<5; ++i)
for (unsigned int j=0; j<5; ++j)
if ((i+2*j+1) % 3 == 0)
sp.add (i,j);
sp.compress ();
ChunkSparseMatrix<double> m(sp);
// first set a few entries
for (unsigned int i=0; i<m.m(); ++i)
for (unsigned int j=0; j<m.n(); ++j)
if ((i+2*j+1) % 3 == 0)
m.set (i,j, i*j*.5+.5);
// then extract the elements (note that
// some may be zero or even outside the
// matrix
AssertDimension(m.end()-m.begin(), m.n_nonzero_elements());
for (unsigned int i=0; i<m.m(); ++i)
{
deallog << "row " << i << ": ";
AssertDimension(m.end(i)-m.begin(i),
m.get_sparsity_pattern().row_length(i));
for (ChunkSparseMatrix<double>::const_iterator it = m.begin(i);
it != m.end(i); ++it)
{
deallog << " done " << (it-m.begin(i)) << ", left " << (it-m.end(i));
}
deallog << std::endl;
}
}
int main ()
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
try
{
const unsigned int chunk_sizes[] = { 1, 2, 4, 5, 7 };
for (unsigned int i=0;<|fim▁hole|> ++i)
test (chunk_sizes[i]);
}
catch (std::exception &exc)
{
deallog << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
deallog << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
deallog << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
deallog << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
};
}<|fim▁end|> | i<sizeof(chunk_sizes)/sizeof(chunk_sizes[0]); |
<|file_name|>identifiers.d.ts<|end_file_name|><|fim▁begin|>import { CompileIdentifierMetadata, CompileTokenMetadata } from './compile_metadata';
export interface IdentifierSpec {
name: string;<|fim▁hole|> static ANALYZE_FOR_ENTRY_COMPONENTS: IdentifierSpec;
static ElementRef: IdentifierSpec;
static NgModuleRef: IdentifierSpec;
static ViewContainerRef: IdentifierSpec;
static ChangeDetectorRef: IdentifierSpec;
static QueryList: IdentifierSpec;
static TemplateRef: IdentifierSpec;
static CodegenComponentFactoryResolver: IdentifierSpec;
static ComponentFactoryResolver: IdentifierSpec;
static ComponentFactory: IdentifierSpec;
static ComponentRef: IdentifierSpec;
static NgModuleFactory: IdentifierSpec;
static NgModuleInjector: IdentifierSpec;
static RegisterModuleFactoryFn: IdentifierSpec;
static Injector: IdentifierSpec;
static ViewEncapsulation: IdentifierSpec;
static ChangeDetectionStrategy: IdentifierSpec;
static SecurityContext: IdentifierSpec;
static LOCALE_ID: IdentifierSpec;
static TRANSLATIONS_FORMAT: IdentifierSpec;
static inlineInterpolate: IdentifierSpec;
static interpolate: IdentifierSpec;
static EMPTY_ARRAY: IdentifierSpec;
static EMPTY_MAP: IdentifierSpec;
static Renderer: IdentifierSpec;
static viewDef: IdentifierSpec;
static elementDef: IdentifierSpec;
static anchorDef: IdentifierSpec;
static textDef: IdentifierSpec;
static directiveDef: IdentifierSpec;
static providerDef: IdentifierSpec;
static queryDef: IdentifierSpec;
static pureArrayDef: IdentifierSpec;
static pureObjectDef: IdentifierSpec;
static purePipeDef: IdentifierSpec;
static pipeDef: IdentifierSpec;
static nodeValue: IdentifierSpec;
static ngContentDef: IdentifierSpec;
static unwrapValue: IdentifierSpec;
static createRendererType2: IdentifierSpec;
static RendererType2: IdentifierSpec;
static ViewDefinition: IdentifierSpec;
static createComponentFactory: IdentifierSpec;
}
export declare function assetUrl(pkg: string, path?: string, type?: string): string;
export declare function resolveIdentifier(identifier: IdentifierSpec): any;
export declare function createIdentifier(identifier: IdentifierSpec): CompileIdentifierMetadata;
export declare function identifierToken(identifier: CompileIdentifierMetadata): CompileTokenMetadata;
export declare function createIdentifierToken(identifier: IdentifierSpec): CompileTokenMetadata;
export declare function createEnumIdentifier(enumType: IdentifierSpec, name: string): CompileIdentifierMetadata;<|fim▁end|> | moduleUrl: string;
runtime: any;
}
export declare class Identifiers { |
<|file_name|>globals_dup.js<|end_file_name|><|fim▁begin|>var globals_dup =
[
[ "a", "globals.html", null ],
[ "b", "globals_0x62.html", null ],
[ "c", "globals_0x63.html", null ],
[ "d", "globals_0x64.html", null ],
[ "e", "globals_0x65.html", null ],
[ "f", "globals_0x66.html", null ],
[ "g", "globals_0x67.html", null ],
[ "h", "globals_0x68.html", null ],
[ "i", "globals_0x69.html", null ],
[ "k", "globals_0x6b.html", null ],
[ "l", "globals_0x6c.html", null ],<|fim▁hole|> [ "p", "globals_0x70.html", null ],
[ "r", "globals_0x72.html", null ],
[ "s", "globals_0x73.html", null ],
[ "u", "globals_0x75.html", null ],
[ "v", "globals_0x76.html", null ],
[ "x", "globals_0x78.html", null ]
];<|fim▁end|> | [ "o", "globals_0x6f.html", null ], |
<|file_name|>faq.py<|end_file_name|><|fim▁begin|># modusite
# Copyright (c) 2006-2010 Phil Christensen
# http://modu.bubblehouse.org
#
#
from modu.persist import storable
class FAQ(storable.Storable):
def __init__(self):<|fim▁hole|> store.ensure_factory('user')
user = store.load_one('user', id=self.answered_by)
return user.username<|fim▁end|> | super(FAQ, self).__init__('faq')
def get_answerer(self):
store = self.get_store() |
<|file_name|>pek1dclasses.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Created on Thu Jun 05 13:55:13 2014
@author: Alison Kirkby
"""
import mtpy.core.edi as mtedi
import os
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as si
import mtpy.utils.exceptions as MTex
import mtpy.utils.calculator as MTcc
import mtpy.analysis.geometry as MTg
import cmath
import math
class Control():
def __init__(self, **input_parameters):
self.run_input = [1, 0, 0.1, 40, 1.05, 1, 0]
# define control file parameters
self.iteration_max = 100 # max number of iterations
self.penalty_type_structure = 6
self.penalty_type_anisotropy = 2 # type of structure and anisotropy penalties
# values for the structure penalty weights
self.penalty_weight_structure = [0.1, 1.0, 10.0]
# values for the anisotropy penalty weights
self.penalty_weight_anisotropy = [0.1, 1.0, 10.0]
self.working_directory = '.'
for key in list(input_parameters.keys()):
setattr(self, key, input_parameters[key])
if not os.path.exists(self.working_directory):
os.mkdir(self.working_directory)
def write_ctlfile(self):
"""
write control file
"""
# create control file
# control file name is hardcoded into software!
ctlfile = open(os.path.join(
self.working_directory, 'inregulm.dat'), 'wb')
# define number of weights
nw_struct = len(self.penalty_weight_structure)
nw_aniso = len(self.penalty_weight_anisotropy)
for thing in [(2, self.iteration_max), (nw_struct, nw_aniso), (self.penalty_type_structure, self.penalty_type_anisotropy)]:
ctlfile.write('%1i%6i\n' % thing)
for thing in [self.penalty_weight_structure, self.penalty_weight_anisotropy]:
ctlfile.write(' '.join([str(i) for i in thing]) + '\n')
ctlfile.close()
print("written control file to {}".format(self.working_directory))
inmodel_kwds = ['inmodel_dictionary']
class Inmodel():
"""
**inmodel_
"""
def __init__(self, **input_parameters):
self.working_directory = '.'
self.inmodel_modeldir = None
self.inmodelfile = 'inmodel.dat'
# dictionary containing values for
self.inmodel_dictionary = {0: [100, 100, 0]}
# inmodel file, in format topdepth: [minres,maxres,strike]
for key in list(input_parameters.keys()):
setattr(self, key, input_parameters[key])
def build_inmodel(self):
"""
build an inmodel file to be used as a constraint
need to give it a dictionary containing values (list of rmin,rmax and strike) and bottom depths
depths are the keys, resistivities are the values
and a modeldir - needs to have the same steps as
the model planned to run.
"""
modelf = open(os.path.join(self.inmodel_modeldir, 'ai1mod.dat'))
modelf.readline()
flag = True
model = []
ii = 1
while flag:
try:
m = [float(i) for i in modelf.readline().strip().split()]
if len(m) > 0:
if ii % 2 == 0:
model.append(m)
ii += 1
except:
flag = False
model = np.array(model)
model[:, 2:] = 0.
mvals = model[:, 2:]
mi = model[:, 0]
mdepths = [0.] + list(model[:, 1])
mthick = np.array([mdepths[i + 1] - mdepths[i]
for i in range(len(mi))])
keys = list(self.inmodel_dictionary.keys())
keys.sort()
for key in keys:
cond = model[:, 1] >= key
mvals[cond] = np.array(self.inmodel_dictionary[key])
self.inmodel = np.vstack([mi, mthick, mvals.T]).T
def write_inmodel(self, wd=None):
"""
"""
if wd is not None:
self.working_directory = wd
if not hasattr(self, 'inmodel'):
self.build_inmodel()
np.savetxt(os.path.join(self.working_directory, 'inmodel.dat'),
self.inmodel,
fmt=['%5i', '%11.4e', '%11.4e', '%11.4e', '%11.4e'])
print("written inmodel file to {}".format(self.working_directory))
def read_inmodel(self):
"""
read the inmodel file
"""
# read in file
inmodel = np.loadtxt(os.path.join(
self.working_directory, self.inmodelfile))
# convert layer thicknesses to depths
depths = np.array([[sum(inmodel[:i, 1]), sum(inmodel[:i + 1, 1])]
for i in range(len(inmodel))]).flatten()
values = np.zeros((len(inmodel) * 2, 5))
ii = 0
for val in inmodel:
for i in range(2):
values[ii] = val
ii += 1
self.inmodel = np.vstack(
[values[:, 0], depths, values[:, 2], values[:, 3], values[:, 4]]).T
def get_boundaries(self):
"""
get points at which the resistivity changes in the inmodel file
"""
if not hasattr(self, 'inmodel'):
try:
self.read_inmodel()
except IOError:
print("please define working directory")
return
data = self.inmodel
bd = []
for i in range(len(data) - 1):
if data[i, 2] != data[i + 1, 2]:
bd.append(data[i, 1])
elif data[i, 2] != data[i + 1, 2]:
bd.append(data[i, 1])
self.boundary_depths = bd
class Data():
"""
deals with input data from 1d inversions, including creating a data file
and reading a data file afterwards to compare with inversion responses
"""
def __init__(self, working_directory, **input_parameters):
self.working_directory = working_directory
self.respfile = 'ai1dat.dat'
self.datafile = None
self.errorfloor = np.ones([2, 2]) * 0.1
self.errorfloor_type = 'relative' # relative, absolute or offdiagonals
self.edipath = None
self.mode = 'I'
for key in list(input_parameters.keys()):
if hasattr(self, key):
setattr(self, key, input_parameters[key])
# default working directory is epath if it is specified, otherwise
# current directory
if self.working_directory is None:
if self.edipath is not None:
self.working_directory = os.path.dirname(self.edipath)
else:
self.working_directory = '.'
def build_data(self):
"""
create data to write to an input file
"""
# read edi file to edi object
self.edi_object = mtedi.Edi(self.edipath)
# define z
zr = np.real(self.edi_object.Z.z)
# sign of imaginary component needs to be reversed for the pek1d
# inversion code
zi = -np.imag(self.edi_object.Z.z)
ze = self.edi_object.Z.z_err
z = zr + 1j * zi
# set errorfloors
if type(self.errorfloor) in [int, float]:
self.errorfloor = np.ones([2, 2]) * self.errorfloor
if self.errorfloor_type in ['relative', 'offdiagonals']:
zer = ze / np.abs(z)
for i in range(2):
for j in range(2):
zer[:, i, j][(zer[:, i, j] < self.errorfloor[
i, j])] = self.errorfloor[i, j]
ze = np.abs(z) * zer
if self.errorfloor_type == 'offdiagonals':
for i in range(2):
for iz in range(len(z)):
if ze[iz, i, i] < ze[iz, i, 1 - i]:
ze[iz, i, i] = ze[iz, i, 1 - i]
elif self.errorfloor_type == 'absolute':
for i in range(2):
for j in range(2):
ze[:, i, j][(ze[:, i, j] < self.errorfloor[
i, j])] = self.errorfloor[i, j]
# define header info for data file
header = '{:>5}\n{:>5}'.format(self.mode, len(self.edi_object.Z.resistivity))
# create data array
data_list = [1. / self.edi_object.Z.freq]
for i in range(2):
for j in range(2):
if self.mode == 'I':
dd = [zr, ze, zi, ze]
for d in dd:
data_list.append(d[:, i, j])
self.header = header
self.data = np.vstack(data_list).T
self.z = zr + 1j * zi
self.z_err = ze
def write_datafile(self, wd=None):
"""
write data to file
"""
if wd is not None:
self.working_directory = wd
self.build_data()
# define format list for writing data file
fmt = ['%14.5f'] + ['%12.5e'] * 16
# define file name and save data file
fname_bas = self.edi_object.station.split('_')[0]
self.datafile = fname_bas + '.dat'
fname = os.path.join(self.working_directory, self.datafile)
np.savetxt(fname, self.data, fmt=fmt, header=self.header, comments='')
def read_datafile(self):
"""
read data file into the data object.
calculate resistivity and phase
"""
if self.datafile is None:
default_files = ['ai1dat.dat', 'ai1mod.dat', 'ai1fit.dat',
'inmodel.dat', 'inregulm.dat']
dlst = [i for i in os.listdir(self.working_directory) if
(i[-4:] == '.dat') and (i not in default_files)]
if len(dlst) == 1:
self.datafile = dlst[0]
else:
print("please define datafile")
return
# define path to file
datafpath = os.path.join(self.working_directory, self.datafile)
self.mode = open(datafpath).readline().strip().split()[0]
data = np.loadtxt(datafpath, skiprows=2)
self.freq = 1. / data[:, 0]
if self.mode == 'I':
zr = np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 1) % 4 == 0])
ze = np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 2) % 4 == 0])
zi = -np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 3) % 4 == 0])
z = zr + 1j * zi
self.z = z.T.reshape(len(z[0]), 2, 2)
self.z_err = ze.T.reshape(len(z[0]), 2, 2)
# make a frequency array that has the same shape as z
freq2 = np.zeros(np.shape(self.z))
for i in range(len(freq2)):
freq2[i, :, :] = 1. / data[:, 0][i]
# calculate resistivity
self.resistivity = 0.2 * np.abs(self.z)**2 / freq2
q = np.zeros(np.shape(self.resistivity))
# q[(zr<0)&(zi<0)] = np.pi
# q[(zr<0)&(zi>0)] = -np.pi
phase = np.zeros([len(self.z), 2, 2])
res = np.zeros([len(self.z), 2, 2])
self.resistivity_err = np.zeros([len(self.z), 2, 2])
self.phase_err = np.zeros([len(self.z), 2, 2])
self.q = q
for iz in range(len(self.z)):
for i in range(2):
for j in range(2):
phase[iz, i, j] = np.rad2deg(
cmath.phase(self.z[iz, i, j]))
res[iz, i, j] = 0.2 * \
np.abs(self.z[iz, i, j])**2 / self.freq[iz]
r_err, phi_err = MTcc.z_error2r_phi_error(
np.real(self.z[iz, i, j]),
self.z_err[iz, i, j],
np.imag(self.z[iz, i, j]),
self.z_err[iz, i, j])
self.resistivity_err[iz, i, j] = \
0.4 * np.abs(self.z[iz, i, j]) /\
self.freq[iz] * r_err
self.phase_err[iz, i, j] = phi_err
phase[phase < -180] += 360
self.phase = phase
self.resistivity = res
elif self.mode == 'R':
res = np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 1) % 4 == 0])
self.resistivity = res.T.reshape(len(res[0]), 2, 2)
res_err = np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 2) % 4 == 0])
self.resistivity_err = res_err.T.reshape(len(res_err[0]), 2, 2)
phs = np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 3) % 4 == 0])
self.phase = phs.T.reshape(len(phs[0]), 2, 2)
phs_err = np.vstack([data[:, i]
for i in range(len(data[0])) if (i - 4) % 4 == 0])
self.phase_err = phs_err.T.reshape(len(phs_err[0]), 2, 2)
def rotate(self, rotation_angle):
"""
use mtpy.analysis.geometry to rotate a z array and recalculate res and phase
"""
from . import pek1dclasses as pek1dc
if not hasattr(self, 'z'):
self.read_datafile()
new_z = np.zeros_like(self.z)
new_ze = np.zeros_like(self.z_err, dtype=float)
# for iz,zarray in enumerate(self.z):
new_z, new_ze = MTg.MTz.rotate_z(
self.z, rotation_angle, z_err_array=self.z_err)
self.z = new_z
self.z_err = new_ze
self.resistivity, self.resistivity_err, self.phase, self.phase_err = \
pek1dc._compute_res_phase(self.z, self.z_err, self.freq)
self.rotation_angle = rotation_angle
class Response():
"""
deals with responses from 1d inversions
"""
def __init__(self, wkdir, **input_parameters):
self.working_directory = wkdir
self.respfile = 'ai1dat.dat'
self.misfit_threshold = 1.1
self.station = None
for key in list(input_parameters.keys()):
if hasattr(self, key):
setattr(self, key, input_parameters[key])
self.read_respfile()
def read_respfile(self):
"""
read respfile into a data object
"""
# define path to file
respfpath = os.path.join(self.working_directory, self.respfile)
respf = open(respfpath)
# find out number of models
n = 0
for line in respf.readlines():
if 'REG' in line:
n += 1
# load model responses into an array
resp = np.genfromtxt(respfpath, skiprows=1, invalid_raise=False)
resmod = np.vstack([resp[:, i]
for i in range(len(resp[0])) if (i - 1) % 2 == 0])
phsmod = np.vstack([resp[:, i] for i in range(
len(resp[0])) if i != 0 and (i - 2) % 2 == 0])
period = resp[:len(resp) / n, 0]
self.resistivity = resmod.T.reshape(n, len(resp) / n, 2, 2)
self._phase = phsmod.T.reshape(n, len(resp) / n, 2, 2)
self.freq = 1. / period
zabs = np.zeros((n, len(resp) / n, 2, 2))
for m in range(n):
for f in range(len(self.freq)):
zabs[m, f] = (self.resistivity[m, f] * self.freq[f] / 0.2)**0.5
zr = zabs * np.cos(np.deg2rad(self._phase))
zi = -zabs * np.sin(np.deg2rad(self._phase))
self.z = zr + 1j * zi
self.phase = -self._phase
def rotate(self, rotation_angle):
"""
use mtpy.analysis.geometry to rotate a z array and recalculate res and phase
"""
from . import pek1dclasses as pek1dc
if not hasattr(self, 'z'):
self.read_respfile()
new_z = np.zeros_like(self.z)
z_err = np.zeros_like(self.z, dtype=float)
for iz, zarray in enumerate(self.z):
new_z[iz], ze = MTg.MTz.rotate_z(zarray, rotation_angle)
self.z = new_z
self.resistivity = np.zeros_like(self.z, dtype=float)
self.phase = np.zeros_like(self.z, dtype=float)
for iz in range(len(self.z)):
r, re, p, pe = pek1dc._compute_res_phase(
self.z[iz], z_err[iz], self.freq)
self.resistivity[iz] = r
# self.resistivity_err[iz] = re
self.phase[iz] = p
# self.phase_err[iz] = pe
self.rotation_angle = rotation_angle
class Fit():
"""
deals with outputs from 1d inversions
"""
def __init__(self, wkdir, **input_parameters):
self.working_directory = wkdir
self.fitfile = 'ai1fit.dat'
self.respfile = 'ai1dat.dat'
self.misfit_threshold = 1.1
self.station = None
for key in list(input_parameters.keys()):
if hasattr(self, key):
setattr(self, key, input_parameters[key])
self.read_fit()
def find_nperiods(self):
"""
find number of periods used in inversion
"""
# find out number of periods
respfpath = os.path.join(self.working_directory, self.respfile)
respf = open(respfpath)
respf.readline()
n = 0
line = respf.readline()
while 'REG' not in line:
line = respf.readline()
n += 1
self.n_periods = n - 1
def read_fit(self):
"""
read fit file to give structure and anisotropy penalties and penalty weights
"""
# load the file with fit values in it
fit = np.loadtxt(os.path.join(self.working_directory, self.fitfile))
# print os.path.join(self.working_directory,self.fitfile)
# print np.shape(fit)
# find number of periods
self.find_nperiods()
# total misfit
self.misfit_mean = (fit[:, 5] / (self.n_periods * 8.))**0.5
# structure and anisotropy penalty
self.penalty_structure = fit[:, 6]
self.penalty_anisotropy = fit[:, 7]
self.weight_structure = fit[:, 2]
self.weight_anisotropy = fit[:, 4]
self.modelno = fit[:, 0]
self.fit = fit
def find_bestmodel(self):
"""
find the smoothest model that fits the data within self.misfit_threshold
"""
self.read_fit()
fit = self.fit
# define parameters
mis = self.misfit_mean
s = self.penalty_structure / np.median(self.penalty_structure)
a = self.penalty_anisotropy / np.median(self.penalty_anisotropy)
# define function to minimise
f = a * s * np.abs(a - s) / (a + s)
# define the parameters relating to the best model
self.params_bestmodel = fit[
f == min(f[mis < min(mis) * self.misfit_threshold])][0]
self.params_fittingmodels = fit[mis < min(mis) * self.misfit_threshold]
class Model():
"""
deals with outputs from 1d inversions
"""
def __init__(self, wkdir, **input_parameters):
self.working_directory = wkdir
self.modelfile = 'ai1mod.dat'
self.respfile = 'ai1dat.dat'
self.fitfile = 'ai1fit.dat'
self.inmodelfile = 'inmodel.dat'
self.datafile = None
self.modelno = 1
self.models = None
self.misfit_threshold = 1.1
self.station = None
self.Fit = None
self.Resp = None
self.Data = None
self.x = 0.
self.y = 0.
self.input_parameters = input_parameters
for key in list(input_parameters.keys()):
if hasattr(self, key):
setattr(self, key, input_parameters[key])
if self.station is None:
self.station = os.path.basename(
self.working_directory).split('_')[0]
self.read_model()
self.read_fit()
self.read_response()
self.read_datafile()
self._calculate_fit_vs_freq()
def read_model(self):
"""
read all models into an array
"""
fpath = os.path.join(self.working_directory, self.modelfile)
# print fpath
nlayers = 0
flag = True
modelf = open(fpath)
modelf.readline()
while flag:
try:
nlayers = int(modelf.readline().strip().split()[0])
except:
flag = False
models = np.genfromtxt(fpath, skiprows=1, invalid_raise=False)
self.models = models.reshape(
0.5 * len(models) / nlayers, 2 * nlayers, 5)
def read_fit(self):
if self.Fit is None:
self.Fit = Fit(self.working_directory, **self.input_parameters)
def read_response(self):
if self.Resp is None:
self.Resp = Response(self.working_directory,
**self.input_parameters)
def read_datafile(self):
if self.Data is None:
self.Data = Data(working_directory=self.working_directory,
**self.input_parameters)
self.Data.read_datafile()
def _calculate_fit_vs_freq(self):
misfit_real = ((np.real(
self.Resp.z[self.modelno - 1]) - np.real(self.Data.z)) / self.Data.z_err)**2
misfit_imag = ((np.imag(
self.Resp.z[self.modelno - 1]) - np.imag(self.Data.z)) / self.Data.z_err)**2
self.Fit.misfit = misfit_real + 1j * misfit_imag
def check_consistent_strike(self, depth,
window=5,
threshold=15.):
"""
check if a particular depth point corresponds to a consistent
strike direction
"""
if self.models is None:
self.read_model()
# get model of interest
model = self.models[self.modelno - 1]
#
depths = model[:, 1]
closest_depth = depths[
np.abs(depths - depth) == np.amin(np.abs(depths - depth))][0]
cdi = list(depths).index(closest_depth)
i1 = max(0, cdi - int(window / 2) * 2 - 1)
i2 = min(len(model) - 2, cdi + int(window / 2) * 2 + 1)
strikes = model[:, -1][i1:i2]
return np.std(strikes) < threshold
def find_max_anisotropy(self, min_depth=0.,
max_depth=None,
strike_window=5,
strike_threshold=10.):
"""
find the point of maximum anisotropy in a model result within a given
depth range. Check that the strike is stable below defined threshold
"""
if self.models is None:
self.read_model()
print(self.station)
# get model of interest
model = self.models[self.modelno - 1]
if max_depth is None:
max_depth = np.amax(model[:, 1])
# get values only between min and max depth
model_filt = model[(model[:, 1] > min_depth) &
(model[:, 1] < max_depth)]
aniso = 1. * model_filt[:, 3] / model_filt[:, 2]
aniso_max = np.amax(aniso)
# define an initial aniso max depth
depth_aniso_max = model_filt[:, 1][aniso == aniso_max][0]
i = 0
while not self.check_consistent_strike(depth_aniso_max,
window=strike_window,
threshold=strike_threshold):
aniso[aniso == aniso_max] = 1.
aniso_max = np.amax(aniso)
depth_aniso_max = model_filt[:, 1][aniso == aniso_max][0]
i += 1
if i > len(model_filt):
print("can't get stable strike")
break
params = model_filt[aniso == aniso_max][0]
# params[-1] = params[-1]%180
self.anisotropy_max_parameters = params
def update_location_from_file(self, xyfile, indices=[0, 999]):
"""
updates x and y location from an xy file with format
station x y
can give indices to search on if the station name in the file
is not exactly the same as defined in the model.
"""
return
class Model_suite():
"""
"""
def __init__(self,
working_directory,
**input_parameters):
self.working_directory = working_directory
self.model_list = []
self.inmodel_list = []
self.modelfile = 'ai1mod.dat'
self.respfile = 'ai1dat.dat'
self.fitfile = 'ai1fit.dat'
self.inmodelfile = 'inmodel.dat'
self.rotation_angle = 0
self.modelno = 1
self.station_list = []
self.station_listfile = None
self.station_search_indices = [0, 999]
self.station_xyfile = None
self.anisotropy_surface_file = 'model%03i_aniso_depth.dat'
for key in list(input_parameters.keys()):
setattr(self, key, input_parameters[key])
if self.station_listfile is not None:
try:
self.station_list = [i.strip() for i in open(
self.station_listfile).readlines()]
except:
print("can't open station list file")
if self.model_list == []:
self.inmodel_list = []
wd = self.working_directory
folder_list = [os.path.join(wd, f) for f in os.listdir(
wd) if os.path.isdir(os.path.join(wd, f))]
if len(self.station_list) > 0:
i1, i2 = self.station_search_indices
folder_list2 = []
for s in self.station_list:
for ff in folder_list:
if str.lower(os.path.basename(ff).split('_')[0][i1:i2]) == str.lower(s):
folder_list2.append(ff)
# print s
folder_list = folder_list2
for folder in folder_list:
try:
model = Model(folder)
model.read_model()
self.model_list.append(model)
except IOError:
print(folder, "model file not found")
try:
inmodel = Inmodel(working_directory=folder)
inmodel.read_inmodel()<|fim▁hole|>
if self.station_xyfile is not None:
self.update_multiple_locations_from_file()
def get_aniso_peak_depth(self,
min_depth=0,
max_depth=None,
strike_threshold=10.,
strike_window=5):
"""
get the min and max resistivities, depth and strike at point of maximum
anisotropy between min and max depth.
min and max depth can be float, integer or numpy array
the depth is only selected if the strike is stable within parameters
given by strike threshold and strike window.
"""
model_params = np.zeros([len(self.model_list), 6])
if type(min_depth) in [float, int]:
min_depth = np.zeros(len(self.model_list)) + min_depth
if type(max_depth) in [float, int]:
max_depth = np.zeros(len(self.model_list)) + max_depth
for i, model in enumerate(self.model_list):
model.modelno = self.modelno
model.find_max_anisotropy(min_depth=min_depth[i],
max_depth=max_depth[i],
strike_window=strike_window,
strike_threshold=strike_threshold)
x, y = model.x, model.y
depth, te, tm, strike = model.anisotropy_max_parameters[1:]
strike = strike + self.rotation_angle
model_params[i] = x, y, depth, te, tm, strike
self.anisotropy_max_parameters = model_params
if '%' in self.anisotropy_surface_file:
self.anisotropy_surface_file = self.anisotropy_surface_file % self.modelno
np.savetxt(os.path.join(self.working_directory,
self.anisotropy_surface_file),
model_params,
header=' '.join(
['x', 'y', 'z', 'resmin', 'resmax', 'strike']),
fmt=['%14.6f', '%14.6f', '%8.2f', '%8.2f', '%8.2f', '%8.2f'])
def update_multiple_locations_from_file(self):
"""
updates multiple x and y locations from an xy file with format
station x y
can give indices to search on if the station name in the file
is not exactly the same as defined in the model.
"""
xy = {}
i1, i2 = self.station_search_indices
for line in open(self.station_xyfile):
line = line.strip().split()
xy[str.lower(line[0])] = [float(line[1]), float(line[2])]
for model in self.model_list:
model.x, model.y = xy[str.lower(model.station[i1:i2])]
self.x = np.array([m.x for m in self.model_list])
self.y = np.array([m.y for m in self.model_list])
def get_median_misfit(self):
"""
"""
n = len(self.model_list)
model_misfits = np.zeros(n)
for m, model in enumerate(self.model_list):
fit = Fit(model.working_directory,
fitfile=self.fitfile,
respfile=self.respfile)
fit.read_fit()
model_misfits[m] = fit.misfit[self.modelno - 1]
self.model_misfits = model_misfits
self.median_misfit = np.median(model_misfits)
def _compute_res_phase(z, z_err, freq):
"""
calculates *resistivity*, *phase*, *resistivity_err*, *phase_err*
values for resistivity are in in Ohm m and phase in degrees.
"""
resistivity_err = np.zeros_like(z_err)
phase_err = np.zeros_like(z_err)
resistivity = np.zeros_like(z, dtype='float')
phase = np.zeros_like(z, dtype='float')
# calculate resistivity and phase
for idx_f in range(len(z)):
for i in range(2):
for j in range(2):
resistivity[idx_f, i, j] = np.abs(z[idx_f, i, j])**2 /\
freq[idx_f] * 0.2
phase[idx_f, i, j] = math.degrees(cmath.phase(
z[idx_f, i, j]))
if z_err is not None:
r_err, phi_err = MTcc.z_error2r_phi_error(
np.real(z[idx_f, i, j]),
z_err[idx_f, i, j],
np.imag(z[idx_f, i, j]),
z_err[idx_f, i, j])
resistivity_err[idx_f, i, j] = \
0.4 * np.abs(z[idx_f, i, j]) /\
freq[idx_f] * r_err
phase_err[idx_f, i, j] = phi_err
return resistivity, resistivity_err, phase, phase_err<|fim▁end|> | self.inmodel_list.append(inmodel)
except IOError:
print("inmodel file not found") |
<|file_name|>0004.py<|end_file_name|><|fim▁begin|>'''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
nums = range(999, 99, -1)<|fim▁hole|>answer = max(palindromeProducts)
print(answer)<|fim▁end|> |
allProducts = [x * y for x in nums for y in nums]
palindromeProducts = [p for p in allProducts if str(p) == str(p)[::-1]]
|
<|file_name|>117PopulatingNextRightPointersInEachNodeII.py<|end_file_name|><|fim▁begin|># Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
def find_next(parent, child):
parent = parent.next
while parent:
if parent.left:
child.next = parent.left
return
elif parent.right:
child.next = parent.right
return
else:<|fim▁hole|>
if not root: return
q = [root]
while q:
nxt = []
for node in q:
if node.left:
if node.right:
node.left.next = node.right
else:
find_next(node, node.left)
nxt.append(node.left)
if node.right:
find_next(node, node.right)
nxt.append(node.right)
q = nxt<|fim▁end|> | parent = parent.next
|
<|file_name|>common.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use syntax::ast;
use syntax::codemap::{span};
use syntax::visit;
use core::hashmap::linear::LinearSet;
use core::str;
use std;
pub fn time<T>(do_it: bool, what: ~str, thunk: &fn() -> T) -> T {
if !do_it { return thunk(); }
let start = std::time::precise_time_s();
let rv = thunk();
let end = std::time::precise_time_s();
io::println(fmt!("time: %3.3f s\t%s", end - start, what));
rv
}
pub fn indent<R>(op: &fn() -> R) -> R {
// Use in conjunction with the log post-processor like `src/etc/indenter`
// to make debug output more readable.
debug!(">>");
let r = op();
debug!("<< (Result = %?)", r);
r
}
pub struct _indenter {
_i: (),
}
impl Drop for _indenter {
fn finalize(&self) { debug!("<<"); }
}
pub fn _indenter(_i: ()) -> _indenter {
_indenter {
_i: ()
}
}
pub fn indenter() -> _indenter {
debug!(">>");
_indenter(())
}
pub fn field_expr(f: ast::field) -> @ast::expr { return f.node.expr; }
pub fn field_exprs(fields: ~[ast::field]) -> ~[@ast::expr] {
fields.map(|f| f.node.expr)
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn loop_query(b: &ast::blk, p: @fn(ast::expr_) -> bool) -> bool {<|fim▁hole|> v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e.node);
match e.node {
// Skip inner loops, since a break in the inner loop isn't a
// break inside the outer loop
ast::expr_loop(*) | ast::expr_while(*)
| ast::expr_loop_body(*) => {}
_ => visit::visit_expr(e, flag, v)
}
};
let v = visit::mk_vt(@visit::Visitor {
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
// Takes a predicate p, returns true iff p is true for any subexpressions
// of b -- skipping any inner loops (loop, while, loop_body)
pub fn block_query(b: &ast::blk, p: @fn(@ast::expr) -> bool) -> bool {
let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool,
v: visit::vt<@mut bool>) = |e, &&flag, v| {
*flag |= p(e);
visit::visit_expr(e, flag, v)
};
let v = visit::mk_vt(@visit::Visitor{
visit_expr: visit_expr,
.. *visit::default_visitor()});
visit::visit_block(b, rs, v);
return *rs;
}
pub fn local_rhs_span(l: @ast::local, def: span) -> span {
match l.node.init {
Some(i) => return i.span,
_ => return def
}
}
pub fn pluralize(n: uint, +s: ~str) -> ~str {
if n == 1 { s }
else { str::concat([s, ~"s"]) }
}
// A set of node IDs (used to keep track of which node IDs are for statements)
pub type stmt_set = @mut LinearSet<ast::node_id>;
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//<|fim▁end|> | let rs = @mut false;
let visit_expr: @fn(@ast::expr,
&&flag: @mut bool, |
<|file_name|>best_hrid_test.py<|end_file_name|><|fim▁begin|># Copyright 2020 Google LLC<|fim▁hole|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests /freebase/object_hints/best_hrid resolution.
/freebase/object_hints/best_hrid specifies a persistent HRID
for an entity. This should be favored over the earlier MQL
algorithm for choosing an HRID based on namespace traversal
and various heuristics.
"""
__author__ = '[email protected] (Nick Thompson)'
import json
import random
import string
import google3
from pymql.mql import error
from pymql.test import mql_fixture
class HRIDTest(mql_fixture.MQLTest):
"""Tests HRID queries using mqlread."""
def setUp(self):
# NOTE: the mock graphd support is broken, so there is no best_hrid.yaml
#self.SetMockPath('data/best_hrid.yaml')
super(HRIDTest, self).setUp()
self.env = {'user': '/user/mw_brendan'}
def newNodeWithHRID(self, best_hrid):
query = """
{
"create":"unless_exists",
"/freebase/object_hints/best_hrid": "%s",
"guid":null
}
""" % best_hrid
self.DoQuery(query, mqlwrite=True)
self.assertEquals(self.mql_result.result["create"],
"created")
return self.mql_result.result["guid"]
def query_assert(self, q, r, exc_response=None, type="mqlread", asof=None):
self.env = {}
if asof is not None:
self.env["as_of_time"] = asof
self.DoQuery(q, exp_response=r, exc_response=exc_response)
def test_missing_hrid(self):
"""Test that MQL still finds an id even if best_hrid is not present"""
q= '{"id":null, "guid":"#9202a8c04000641f8000000000092a01", "mid":null}'
r= ('{"guid": "#9202a8c04000641f8000000000092a01",'
'"id": "/en/sting","mid":"/m/0lbj1"}')
self.query_assert(q,r)
def test_good_hrid(self):
"""Test /type/type, a best_hrid that agrees with the MQL heuristics"""
# /m/0j == /type/type
q= '{"id":null, "mid":"/m/0j", "/freebase/object_hints/best_hrid":null}'
r= ('{"id": "/type/type","mid":"/m/0j",'
'"/freebase/object_hints/best_hrid":"/type/type"}')
self.query_assert(q, r)
def test_hrid_override(self):
"""Create a new node with a bogus best_hrid.
The old MQL heuristics will fail; check that best_hrid works.
"""
best_hrid = ('/user/nix/random_test_hrid/' +
''.join(random.choice(string.ascii_lowercase)
for x in range(16)))
guid = self.newNodeWithHRID(best_hrid)
q= (('{"id":null, "guid":"%(guid)s",'
'"/freebase/object_hints/best_hrid":null}' %
{"guid":guid}))
r= (('{"id": "%(best_hrid)s","guid":"%(guid)s",'
'"/freebase/object_hints/best_hrid":"%(best_hrid)s"}') %
{"guid":guid,"best_hrid":best_hrid})
self.query_assert(q, r)
if __name__ == '__main__':
mql_fixture.main()<|fim▁end|> | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at |
<|file_name|>test33.py<|end_file_name|><|fim▁begin|>'d'
def x():
print j
j = 0
<|fim▁hole|><|fim▁end|> | def y():
for x in []:
print x |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from django.views.generic import View
from django.conf import settings
from geonode.base.enumerations import LINK_TYPES as _LT
# from geonode.base.models import Link
from geonode.utils import json_response
from geonode.geoserver import ows
LINK_TYPES = [L for L in _LT if L.startswith("OGC:")]
class OWSListView(View):
def get(self, request):
out = {'success': True}
data = []
out['data'] = data
# per-layer links
# for link in Link.objects.filter(link_type__in=LINK_TYPES): # .distinct('url'):
# data.append({'url': link.url, 'type': link.link_type})
data.append({'url': ows._wcs_get_capabilities(), 'type': 'OGC:WCS'})
data.append({'url': ows._wfs_get_capabilities(), 'type': 'OGC:WFS'})
data.append({'url': ows._wms_get_capabilities(), 'type': 'OGC:WMS'})
# catalogue from configuration
for catname, catconf in settings.CATALOGUE.items():
data.append({'url': catconf['URL'], 'type': 'OGC:CSW'})
# main site url
data.append({'url': settings.SITEURL, 'type': 'WWW:LINK'})<|fim▁hole|><|fim▁end|> | return json_response(out)
ows_endpoints = OWSListView.as_view() |
<|file_name|>get_user_input.cpp<|end_file_name|><|fim▁begin|>/* Copyright (C) 2012-2014 Carlos Pais
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "get_user_input.h"
#include <QTextCodec>
GetUserInput::GetUserInput(QObject *parent) :
Action(parent)
{
init();
}
GetUserInput::GetUserInput(const QVariantMap& data, QObject *parent):
Action(data, parent)
{
init();
loadInternal(data);
}
void GetUserInput::init()
{
setType(GameObjectMetaType::GetUserInput);
}
void GetUserInput::loadData(const QVariantMap & data, bool internal)
{
if (!internal)
Action::loadData(data, internal);
if (data.contains("message") && data.value("message").type() == QVariant::String)
setMessage(data.value("message").toString());
if (data.contains("variable") && data.value("variable").type() == QVariant::String)
setVariable(data.value("variable").toString());
if (data.contains("defaultValue") && data.value("defaultValue").type() == QVariant::String)
setDefaultValue(data.value("defaultValue").toString());
}
QString GetUserInput::variable()
{
return mVariable;<|fim▁hole|>{
if (var != mVariable) {
mVariable = var;
notify("variable", mVariable);
}
}
QString GetUserInput::message()
{
return mMessage;
}
void GetUserInput::setMessage(const QString & msg)
{
if (msg != mMessage) {
mMessage = msg;
notify("message", mMessage);
}
}
QString GetUserInput::defaultValue()
{
return mDefaultValue;
}
void GetUserInput::setDefaultValue(const QString & value)
{
if (value != mDefaultValue) {
mDefaultValue = value;
notify("defaultValue", mDefaultValue);
}
}
QString GetUserInput::displayText() const
{
QString var("");
QString text(tr("Prompt") + " ");
text += QString("\"%1\"").arg(mMessage);
if (mVariable.size())
var = " " + tr("and store reply in") + " $" + mVariable;
text += var;
return text;
}
QVariantMap GetUserInput::toJsonObject(bool internal) const
{
QVariantMap object = Action::toJsonObject(internal);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
if (! codec)
codec = QTextCodec::codecForLocale();
object.insert("message", mMessage);
object.insert("variable", mVariable);
object.insert("defaultValue", mDefaultValue);
return object;
}<|fim▁end|> | }
void GetUserInput::setVariable(const QString & var) |
<|file_name|>ObjectConstants.js<|end_file_name|><|fim▁begin|>(function () {
"use strict";
/**
* This module have an ability to contain constants.
* No one can reinitialize any of already initialized constants
*/
var module = (function () {
var constants = {},
hasOwnProperty = Object.prototype.hasOwnProperty,
prefix = (Math.random() + "_").slice(2),
isAllowed;
/**
* This private method checks if value is acceptable
* @param value {String|Number|Boolean} - the value of the constant
* @returns {boolean}
* @private
*/
isAllowed = function (value) {
switch (typeof value) {
case "number":
return true;
case "string":
return true;
case "boolean":
return true;
default:
return false;
}
};
return {<|fim▁hole|> * @param name {String} - the name of the constant
* @returns {String|Number|Boolean|null}
*/
getConstant: function (name) {
if (this.isDefined(name) === true) {
return constants[prefix + name];
}
return undefined;
},
/**
* Setter
* @param name {String} - the name of the constant
* @param value {String|Number|Boolean} - the value of the constant
* @returns {boolean}
*/
setConstant: function (name, value) {
if (isAllowed(value) !== true) {
return false;
}
if (this.isDefined(name) === true) {
return false;
}
constants[prefix + name] = value;
return true;
},
/**
* This method checks if constant is already defined
* @param name {String} - the name of the constant
* @returns {boolean}
*/
isDefined: function (name) {
return hasOwnProperty.call(constants, prefix + name);
}
};
})();
/**Testing*/
module.setConstant("test", 123);
print("test == " + module.getConstant("test"));
print("idDefined(\"test\") == " + module.isDefined("test"));
print("test2 == " + module.getConstant("test2"));
print("idDefined(\"test2\") == " + module.isDefined("test2"));
print("");
module.setConstant("test", 321);
print("test == " + module.getConstant("test"));
print("");
module.setConstant("test3", {a: 123});
print("test3 == " + module.getConstant("test3"));
})();<|fim▁end|> | /**
* Constant getter |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Unit tests for reverse URL lookups.
"""
from __future__ import unicode_literals
import sys
import threading
import unittest
from admin_scripts.tests import AdminScriptTestCase
from django.conf import settings
from django.conf.urls import include, url
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.http import (
HttpRequest, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.shortcuts import redirect
from django.test import (
SimpleTestCase, TestCase, ignore_warnings, override_settings,
)
from django.test.utils import override_script_prefix
from django.urls import (
NoReverseMatch, RegexURLPattern, RegexURLResolver, Resolver404,
ResolverMatch, get_callable, get_resolver, resolve, reverse, reverse_lazy,
)
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from . import middleware, urlconf_outer, views
from .utils import URLObject
from .views import empty_view
resolve_test_data = (
# These entries are in the format: (path, url_name, app_name, namespace, view_name, func, args, kwargs)
# Simple case
('/normal/42/37/', 'normal-view', '', '', 'normal-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}),
(
'/view_class/42/37/', 'view-class', '', '', 'view-class', views.view_class_instance, tuple(),
{'arg1': '42', 'arg2': '37'}
),
(
'/included/normal/42/37/', 'inc-normal-view', '', '', 'inc-normal-view', views.empty_view, tuple(),
{'arg1': '42', 'arg2': '37'}
),
(
'/included/view_class/42/37/', 'inc-view-class', '', '', 'inc-view-class', views.view_class_instance, tuple(),
{'arg1': '42', 'arg2': '37'}
),
# Unnamed args are dropped if you have *any* kwargs in a pattern
('/mixed_args/42/37/', 'mixed-args', '', '', 'mixed-args', views.empty_view, tuple(), {'arg2': '37'}),
(
'/included/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(),
{'arg2': '37'}
),
(
'/included/12/mixed_args/42/37/', 'inc-mixed-args', '', '', 'inc-mixed-args', views.empty_view, tuple(),
{'arg2': '37'}
),
# Unnamed views should have None as the url_name. Regression data for #21157.
(
'/unnamed/normal/42/37/', None, '', '', 'urlpatterns_reverse.views.empty_view', views.empty_view, tuple(),
{'arg1': '42', 'arg2': '37'}
),
(
'/unnamed/view_class/42/37/', None, '', '', 'urlpatterns_reverse.views.ViewClass', views.view_class_instance,
tuple(), {'arg1': '42', 'arg2': '37'}
),
# If you have no kwargs, you get an args list.
('/no_kwargs/42/37/', 'no-kwargs', '', '', 'no-kwargs', views.empty_view, ('42', '37'), {}),
('/included/no_kwargs/42/37/', 'inc-no-kwargs', '', '', 'inc-no-kwargs', views.empty_view, ('42', '37'), {}),
(
'/included/12/no_kwargs/42/37/', 'inc-no-kwargs', '', '', 'inc-no-kwargs', views.empty_view,
('12', '42', '37'), {}
),
# Namespaces
(
'/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'test-ns1:urlobject-view',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'test-ns3:urlobject-view',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/ns-included1/normal/42/37/', 'inc-normal-view', '', 'inc-ns1', 'inc-ns1:inc-normal-view', views.empty_view,
tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'test-ns3:urlobject-view',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/default/inner/42/37/', 'urlobject-view', 'testapp', 'testapp', 'testapp:urlobject-view', views.empty_view,
tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/other2/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns2', 'other-ns2:urlobject-view',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'other-ns1:urlobject-view',
views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
# Nested namespaces
(
'/ns-included1/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:test-ns3',
'inc-ns1:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', 'testapp',
'inc-ns1:inc-ns4:inc-ns2:test-ns3', 'inc-ns1:inc-ns4:inc-ns2:test-ns3:urlobject-view', views.empty_view,
tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/app-included/test3/inner/42/37/', 'urlobject-view', 'inc-app:testapp', 'inc-app:test-ns3',
'inc-app:test-ns3:urlobject-view', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}
),
(
'/app-included/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', 'inc-app:testapp',
'inc-app:inc-ns4:inc-ns2:test-ns3', 'inc-app:inc-ns4:inc-ns2:test-ns3:urlobject-view', views.empty_view,
tuple(), {'arg1': '42', 'arg2': '37'}
),
# Namespaces capturing variables
('/inc70/', 'inner-nothing', '', 'inc-ns5', 'inc-ns5:inner-nothing', views.empty_view, tuple(), {'outer': '70'}),
(
'/inc78/extra/foobar/', 'inner-extra', '', 'inc-ns5', 'inc-ns5:inner-extra', views.empty_view, tuple(),
{'outer': '78', 'extra': 'foobar'}
),
)
test_data = (
('places', '/places/3/', [3], {}),
('places', '/places/3/', ['3'], {}),
('places', NoReverseMatch, ['a'], {}),
('places', NoReverseMatch, [], {}),
('places?', '/place/', [], {}),
('places+', '/places/', [], {}),
('places*', '/place/', [], {}),
('places2?', '/', [], {}),
('places2+', '/places/', [], {}),
('places2*', '/', [], {}),
('places3', '/places/4/', [4], {}),
('places3', '/places/harlem/', ['harlem'], {}),
('places3', NoReverseMatch, ['harlem64'], {}),
('places4', '/places/3/', [], {'id': 3}),
('people', NoReverseMatch, [], {}),
('people', '/people/adrian/', ['adrian'], {}),
('people', '/people/adrian/', [], {'name': 'adrian'}),
('people', NoReverseMatch, ['name with spaces'], {}),
('people', NoReverseMatch, [], {'name': 'name with spaces'}),
('people2', '/people/name/', [], {}),
('people2a', '/people/name/fred/', ['fred'], {}),
('people_backref', '/people/nate-nate/', ['nate'], {}),
('people_backref', '/people/nate-nate/', [], {'name': 'nate'}),
('optional', '/optional/fred/', [], {'name': 'fred'}),
('optional', '/optional/fred/', ['fred'], {}),
('named_optional', '/optional/1/', [1], {}),
('named_optional', '/optional/1/', [], {'arg1': 1}),
('named_optional', '/optional/1/2/', [1, 2], {}),
('named_optional', '/optional/1/2/', [], {'arg1': 1, 'arg2': 2}),
('named_optional_terminated', '/optional/1/2/', [1, 2], {}),
('named_optional_terminated', '/optional/1/2/', [], {'arg1': 1, 'arg2': 2}),
('hardcoded', '/hardcoded/', [], {}),
('hardcoded2', '/hardcoded/doc.pdf', [], {}),
('people3', '/people/il/adrian/', [], {'state': 'il', 'name': 'adrian'}),
('people3', NoReverseMatch, [], {'state': 'il'}),
('people3', NoReverseMatch, [], {'name': 'adrian'}),
('people4', NoReverseMatch, [], {'state': 'il', 'name': 'adrian'}),
('people6', '/people/il/test/adrian/', ['il/test', 'adrian'], {}),
('people6', '/people//adrian/', ['adrian'], {}),
('range', '/character_set/a/', [], {}),
('range2', '/character_set/x/', [], {}),
('price', '/price/$10/', ['10'], {}),
('price2', '/price/$10/', ['10'], {}),
('price3', '/price/$10/', ['10'], {}),
('product', '/product/chocolate+($2.00)/', [], {'price': '2.00', 'product': 'chocolate'}),
('headlines', '/headlines/2007.5.21/', [], dict(year=2007, month=5, day=21)),
(
'windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [],
dict(drive_name='C', path=r'Documents and Settings\spam')
),
('special', r'/special_chars/~@+%5C$*%7C/', [r'~@+\$*|'], {}),
('special', r'/special_chars/some%20resource/', [r'some resource'], {}),
('special', r'/special_chars/10%25%20complete/', [r'10% complete'], {}),
('special', r'/special_chars/some%20resource/', [], {'chars': r'some resource'}),
('special', r'/special_chars/10%25%20complete/', [], {'chars': r'10% complete'}),
('special', NoReverseMatch, [''], {}),
('mixed', '/john/0/', [], {'name': 'john'}),
('repeats', '/repeats/a/', [], {}),
('repeats2', '/repeats/aa/', [], {}),
('repeats3', '/repeats/aa/', [], {}),
('insensitive', '/CaseInsensitive/fred', ['fred'], {}),
('test', '/test/1', [], {}),
('test2', '/test/2', [], {}),
('inner-nothing', '/outer/42/', [], {'outer': '42'}),
('inner-nothing', '/outer/42/', ['42'], {}),
('inner-nothing', NoReverseMatch, ['foo'], {}),
('inner-extra', '/outer/42/extra/inner/', [], {'extra': 'inner', 'outer': '42'}),
('inner-extra', '/outer/42/extra/inner/', ['42', 'inner'], {}),
('inner-extra', NoReverseMatch, ['fred', 'inner'], {}),
('inner-no-kwargs', '/outer-no-kwargs/42/inner-no-kwargs/1/', ['42', '1'], {}),
('disjunction', NoReverseMatch, ['foo'], {}),
('inner-disjunction', NoReverseMatch, ['10', '11'], {}),
('extra-places', '/e-places/10/', ['10'], {}),
('extra-people', '/e-people/fred/', ['fred'], {}),
('extra-people', '/e-people/fred/', [], {'name': 'fred'}),
('part', '/part/one/', [], {'value': 'one'}),
('part', '/prefix/xx/part/one/', [], {'value': 'one', 'prefix': 'xx'}),
('part2', '/part2/one/', [], {'value': 'one'}),
('part2', '/part2/', [], {}),
('part2', '/prefix/xx/part2/one/', [], {'value': 'one', 'prefix': 'xx'}),
('part2', '/prefix/xx/part2/', [], {'prefix': 'xx'}),
# Tests for nested groups. Nested capturing groups will only work if you
# *only* supply the correct outer group.
('nested-noncapture', '/nested/noncapture/opt', [], {'p': 'opt'}),
('nested-capture', '/nested/capture/opt/', ['opt/'], {}),
('nested-capture', NoReverseMatch, [], {'p': 'opt'}),
('nested-mixedcapture', '/nested/capture/mixed/opt', ['opt'], {}),
('nested-mixedcapture', NoReverseMatch, [], {'p': 'opt'}),
('nested-namedcapture', '/nested/capture/named/opt/', [], {'outer': 'opt/'}),
('nested-namedcapture', NoReverseMatch, [], {'outer': 'opt/', 'inner': 'opt'}),
('nested-namedcapture', NoReverseMatch, [], {'inner': 'opt'}),
('non_path_include', '/includes/non_path_include/', [], {}),
# Tests for #13154
('defaults', '/defaults_view1/3/', [], {'arg1': 3, 'arg2': 1}),
('defaults', '/defaults_view2/3/', [], {'arg1': 3, 'arg2': 2}),
('defaults', NoReverseMatch, [], {'arg1': 3, 'arg2': 3}),
('defaults', NoReverseMatch, [], {'arg2': 1}),
# Security tests
('security', '/%2Fexample.com/security/', ['/example.com'], {}),
)
@override_settings(ROOT_URLCONF='urlpatterns_reverse.no_urls')
class NoURLPatternsTests(SimpleTestCase):
def test_no_urls_exception(self):
"""
RegexURLResolver should raise an exception when no urlpatterns exist.
"""
resolver = RegexURLResolver(r'^$', settings.ROOT_URLCONF)
with self.assertRaisesMessage(
ImproperlyConfigured,
"The included URLconf 'urlpatterns_reverse.no_urls' does not "
"appear to have any patterns in it. If you see valid patterns in "
"the file then the issue is probably caused by a circular import."
):
getattr(resolver, 'url_patterns')
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')
class URLPatternReverse(SimpleTestCase):
def test_urlpattern_reverse(self):
for name, expected, args, kwargs in test_data:
try:
got = reverse(name, args=args, kwargs=kwargs)
except NoReverseMatch:
self.assertEqual(expected, NoReverseMatch)
else:
self.assertEqual(got, expected)
def test_reverse_none(self):
# Reversing None should raise an error, not return the last un-named view.
with self.assertRaises(NoReverseMatch):
reverse(None)
@override_script_prefix('/{{invalid}}/')
def test_prefix_braces(self):
self.assertEqual(
'/%7B%7Binvalid%7D%7D/includes/non_path_include/',
reverse('non_path_include')
)
def test_prefix_parenthesis(self):
# Parentheses are allowed and should not cause errors or be escaped
with override_script_prefix('/bogus)/'):
self.assertEqual(
'/bogus)/includes/non_path_include/',
reverse('non_path_include')
)
with override_script_prefix('/(bogus)/'):
self.assertEqual(
'/(bogus)/includes/non_path_include/',
reverse('non_path_include')
)
@override_script_prefix('/bump%20map/')
def test_prefix_format_char(self):
self.assertEqual(
'/bump%2520map/includes/non_path_include/',
reverse('non_path_include')
)
@override_script_prefix('/%7Eme/')
def test_non_urlsafe_prefix_with_args(self):
# Regression for #20022, adjusted for #24013 because ~ is an unreserved
# character. Tests whether % is escaped.
self.assertEqual('/%257Eme/places/1/', reverse('places', args=[1]))
def test_patterns_reported(self):
# Regression for #17076
with self.assertRaisesMessage(NoReverseMatch, r"1 pattern(s) tried: ['people/(?P<name>\\w+)/$']"):
# this url exists, but requires an argument
reverse("people", args=[])
@override_script_prefix('/script:name/')
def test_script_name_escaping(self):
self.assertEqual(
reverse('optional', args=['foo:bar']),
'/script:name/optional/foo:bar/'
)
def test_reverse_returns_unicode(self):
name, expected, args, kwargs = test_data[0]
self.assertIsInstance(
reverse(name, args=args, kwargs=kwargs),
six.text_type
)
class ResolverTests(SimpleTestCase):
@ignore_warnings(category=RemovedInDjango20Warning)
def test_resolver_repr(self):
"""
Test repr of RegexURLResolver, especially when urlconf_name is a list
(#17892).
"""
# Pick a resolver from a namespaced URLconf
resolver = get_resolver('urlpatterns_reverse.namespace_urls')
sub_resolver = resolver.namespace_dict['test-ns1'][1]
self.assertIn('<RegexURLPattern list>', repr(sub_resolver))
def test_reverse_lazy_object_coercion_by_resolve(self):
"""
Verifies lazy object returned by reverse_lazy is coerced to
text by resolve(). Previous to #21043, this would raise a TypeError.
"""
urls = 'urlpatterns_reverse.named_urls'
proxy_url = reverse_lazy('named-url1', urlconf=urls)
resolver = get_resolver(urls)
resolver.resolve(proxy_url)
def test_resolver_reverse(self):
resolver = get_resolver('urlpatterns_reverse.named_urls')
self.assertEqual(resolver.reverse('named-url1'), '')
self.assertEqual(resolver.reverse('named-url2', 'arg'), 'extra/arg/')
self.assertEqual(resolver.reverse('named-url2', extra='arg'), 'extra/arg/')
def test_non_regex(self):
"""
A Resolver404 is raised if resolving doesn't meet the basic
requirements of a path to match - i.e., at the very least, it matches
the root pattern '^/'. Never return None from resolve() to prevent a
TypeError from occuring later (#10834).
"""
with self.assertRaises(Resolver404):
resolve('')
with self.assertRaises(Resolver404):
resolve('a')
with self.assertRaises(Resolver404):
resolve('\\')
with self.assertRaises(Resolver404):
resolve('.')
def test_404_tried_urls_have_names(self):
"""
The list of URLs that come back from a Resolver404 exception contains
a list in the right format for printing out in the DEBUG 404 page with
both the patterns and URL names, if available.
"""
urls = 'urlpatterns_reverse.named_urls'
# this list matches the expected URL types and names returned when
# you try to resolve a non-existent URL in the first level of included
# URLs in named_urls.py (e.g., '/included/non-existent-url')
url_types_names = [
[{'type': RegexURLPattern, 'name': 'named-url1'}],
[{'type': RegexURLPattern, 'name': 'named-url2'}],
[{'type': RegexURLPattern, 'name': None}],
[{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': 'named-url3'}],
[{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': 'named-url4'}],
[{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': None}],
[{'type': RegexURLResolver}, {'type': RegexURLResolver}],
]
with self.assertRaisesMessage(Resolver404, b'tried' if six.PY2 else 'tried') as cm:
resolve('/included/non-existent-url', urlconf=urls)
e = cm.exception
# make sure we at least matched the root ('/') url resolver:
self.assertIn('tried', e.args[0])
tried = e.args[0]['tried']
self.assertEqual(
len(e.args[0]['tried']),
len(url_types_names),
'Wrong number of tried URLs returned. Expected %s, got %s.' % (
len(url_types_names), len(e.args[0]['tried'])
)
)
for tried, expected in zip(e.args[0]['tried'], url_types_names):
for t, e in zip(tried, expected):
self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])
if 'name' in e:
if not e['name']:
self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name)
else:
self.assertEqual(
t.name,
e['name'],
'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name)
)
def test_namespaced_view_detail(self):
resolver = get_resolver('urlpatterns_reverse.nested_urls')
self.assertTrue(resolver._is_callback('urlpatterns_reverse.nested_urls.view1'))
self.assertTrue(resolver._is_callback('urlpatterns_reverse.nested_urls.view2'))
self.assertTrue(resolver._is_callback('urlpatterns_reverse.nested_urls.View3'))
self.assertFalse(resolver._is_callback('urlpatterns_reverse.nested_urls.blub'))
@unittest.skipIf(six.PY2, "Python 2 doesn't support __qualname__.")
def test_view_detail_as_method(self):
# Views which have a class name as part of their path.
resolver = get_resolver('urlpatterns_reverse.method_view_urls')
self.assertTrue(resolver._is_callback('urlpatterns_reverse.method_view_urls.ViewContainer.method_view'))
self.assertTrue(resolver._is_callback('urlpatterns_reverse.method_view_urls.ViewContainer.classmethod_view'))
def test_populate_concurrency(self):
"""
RegexURLResolver._populate() can be called concurrently, but not more
than once per thread (#26888).
"""
resolver = RegexURLResolver(r'^/', 'urlpatterns_reverse.urls')
resolver._local.populating = True
thread = threading.Thread(target=resolver._populate)
thread.start()
thread.join()
self.assertNotEqual(resolver._reverse_dict, {})
@override_settings(ROOT_URLCONF='urlpatterns_reverse.reverse_lazy_urls')
class ReverseLazyTest(TestCase):
def test_redirect_with_lazy_reverse(self):
response = self.client.get('/redirect/')
self.assertRedirects(response, "/redirected_to/", status_code=302)
def test_user_permission_with_lazy_reverse(self):
alfred = User.objects.create_user('alfred', '[email protected]', password='testpw')
response = self.client.get('/login_required_view/')
self.assertRedirects(response, "/login/?next=/login_required_view/", status_code=302)
self.client.force_login(alfred)
response = self.client.get('/login_required_view/')
self.assertEqual(response.status_code, 200)
def test_inserting_reverse_lazy_into_string(self):
self.assertEqual(
'Some URL: %s' % reverse_lazy('some-login-page'),
'Some URL: /login/'
)
if six.PY2:
self.assertEqual(
b'Some URL: %s' % reverse_lazy('some-login-page'),
'Some URL: /login/'
)
class ReverseLazySettingsTest(AdminScriptTestCase):
"""
reverse_lazy can be used in settings without causing a circular
import error.
"""
def setUp(self):
self.write_settings('settings.py', extra="""
from django.urls import reverse_lazy
LOGIN_URL = reverse_lazy('login')""")
def tearDown(self):
self.remove_settings('settings.py')
def test_lazy_in_settings(self):
out, err = self.run_manage(['check'])
self.assertNoOutput(err)
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')
class ReverseShortcutTests(SimpleTestCase):
def test_redirect_to_object(self):
# We don't really need a model; just something with a get_absolute_url
class FakeObj(object):
def get_absolute_url(self):
return "/hi-there/"
res = redirect(FakeObj())
self.assertIsInstance(res, HttpResponseRedirect)
self.assertEqual(res.url, '/hi-there/')
res = redirect(FakeObj(), permanent=True)
self.assertIsInstance(res, HttpResponsePermanentRedirect)
self.assertEqual(res.url, '/hi-there/')
def test_redirect_to_view_name(self):
res = redirect('hardcoded2')
self.assertEqual(res.url, '/hardcoded/doc.pdf')
res = redirect('places', 1)
self.assertEqual(res.url, '/places/1/')
res = redirect('headlines', year='2008', month='02', day='17')
self.assertEqual(res.url, '/headlines/2008.02.17/')
with self.assertRaises(NoReverseMatch):
redirect('not-a-view')
def test_redirect_to_url(self):
res = redirect('/foo/')
self.assertEqual(res.url, '/foo/')
res = redirect('http://example.com/')
self.assertEqual(res.url, 'http://example.com/')
# Assert that we can redirect using UTF-8 strings
res = redirect('/æøå/abc/')
self.assertEqual(res.url, '/%C3%A6%C3%B8%C3%A5/abc/')
# Assert that no imports are attempted when dealing with a relative path
# (previously, the below would resolve in a UnicodeEncodeError from __import__ )
res = redirect('/æøå.abc/')
self.assertEqual(res.url, '/%C3%A6%C3%B8%C3%A5.abc/')
res = redirect('os.path')
self.assertEqual(res.url, 'os.path')
def test_no_illegal_imports(self):
# modules that are not listed in urlpatterns should not be importable
redirect("urlpatterns_reverse.nonimported_module.view")
self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules)
def test_reverse_by_path_nested(self):
# Views added to urlpatterns using include() should be reversible.
from .views import nested_view
self.assertEqual(reverse(nested_view), '/includes/nested_path/')
def test_redirect_view_object(self):
from .views import absolute_kwargs_view
res = redirect(absolute_kwargs_view)
self.assertEqual(res.url, '/absolute_arg_view/')
with self.assertRaises(NoReverseMatch):
redirect(absolute_kwargs_view, wrong_argument=None)
@override_settings(ROOT_URLCONF='urlpatterns_reverse.namespace_urls')
@ignore_warnings(category=RemovedInDjango20Warning)
class NamespaceTests(SimpleTestCase):
def test_ambiguous_object(self):
"Names deployed via dynamic URL objects that require namespaces can't be resolved"
with self.assertRaises(NoReverseMatch):
reverse('urlobject-view')
with self.assertRaises(NoReverseMatch):
reverse('urlobject-view', args=[37, 42])
with self.assertRaises(NoReverseMatch):
reverse('urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
def test_ambiguous_urlpattern(self):
"Names deployed via dynamic URL objects that require namespaces can't be resolved"
with self.assertRaises(NoReverseMatch):
reverse('inner-nothing')
with self.assertRaises(NoReverseMatch):
reverse('inner-nothing', args=[37, 42])
with self.assertRaises(NoReverseMatch):
reverse('inner-nothing', kwargs={'arg1': 42, 'arg2': 37})
def test_non_existent_namespace(self):
"Non-existent namespaces raise errors"
with self.assertRaises(NoReverseMatch):
reverse('blahblah:urlobject-view')<|fim▁hole|> "Normal lookups work as expected"
self.assertEqual('/normal/', reverse('normal-view'))
self.assertEqual('/normal/37/42/', reverse('normal-view', args=[37, 42]))
self.assertEqual('/normal/42/37/', reverse('normal-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/+%5C$*/', reverse('special-view'))
def test_simple_included_name(self):
"Normal lookups work on names included from other patterns"
self.assertEqual('/included/normal/', reverse('inc-normal-view'))
self.assertEqual('/included/normal/37/42/', reverse('inc-normal-view', args=[37, 42]))
self.assertEqual('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/included/+%5C$*/', reverse('inc-special-view'))
def test_namespace_object(self):
"Dynamic URL objects can be found using a namespace"
self.assertEqual('/test1/inner/', reverse('test-ns1:urlobject-view'))
self.assertEqual('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37, 42]))
self.assertEqual('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/test1/inner/+%5C$*/', reverse('test-ns1:urlobject-special-view'))
def test_app_object(self):
"Dynamic URL objects can return a (pattern, app_name) 2-tuple, and include() can set the namespace"
self.assertEqual('/newapp1/inner/', reverse('new-ns1:urlobject-view'))
self.assertEqual('/newapp1/inner/37/42/', reverse('new-ns1:urlobject-view', args=[37, 42]))
self.assertEqual('/newapp1/inner/42/37/', reverse('new-ns1:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/newapp1/inner/+%5C$*/', reverse('new-ns1:urlobject-special-view'))
def test_app_object_default_namespace(self):
"Namespace defaults to app_name when including a (pattern, app_name) 2-tuple"
self.assertEqual('/new-default/inner/', reverse('newapp:urlobject-view'))
self.assertEqual('/new-default/inner/37/42/', reverse('newapp:urlobject-view', args=[37, 42]))
self.assertEqual(
'/new-default/inner/42/37/', reverse('newapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/new-default/inner/+%5C$*/', reverse('newapp:urlobject-special-view'))
def test_embedded_namespace_object(self):
"Namespaces can be installed anywhere in the URL pattern tree"
self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view'))
self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual(
'/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/included/test3/inner/+%5C$*/', reverse('test-ns3:urlobject-special-view'))
def test_namespace_pattern(self):
"Namespaces can be applied to include()'d urlpatterns"
self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view'))
self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37, 42]))
self.assertEqual(
'/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/ns-included1/+%5C$*/', reverse('inc-ns1:inc-special-view'))
def test_app_name_pattern(self):
"Namespaces can be applied to include()'d urlpatterns that set an app_name attribute"
self.assertEqual('/app-included1/normal/', reverse('app-ns1:inc-normal-view'))
self.assertEqual('/app-included1/normal/37/42/', reverse('app-ns1:inc-normal-view', args=[37, 42]))
self.assertEqual(
'/app-included1/normal/42/37/', reverse('app-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/app-included1/+%5C$*/', reverse('app-ns1:inc-special-view'))
def test_namespace_pattern_with_variable_prefix(self):
"When using an include with namespaces when there is a regex variable in front of it"
self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', kwargs={'outer': 42}))
self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', args=[42]))
self.assertEqual(
'/ns-outer/42/normal/37/4/',
reverse('inc-outer:inc-normal-view', kwargs={'outer': 42, 'arg1': 37, 'arg2': 4})
)
self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', args=[42, 37, 4]))
self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', kwargs={'outer': 42}))
self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', args=[42]))
def test_multiple_namespace_pattern(self):
"Namespaces can be embedded"
self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual(
'/ns-included1/test3/inner/42/37/',
reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:test-ns3:urlobject-special-view'))
def test_nested_namespace_pattern(self):
"Namespaces can be nested"
self.assertEqual(
'/ns-included1/ns-included4/ns-included1/test3/inner/',
reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view')
)
self.assertEqual(
'/ns-included1/ns-included4/ns-included1/test3/inner/37/42/',
reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37, 42])
)
self.assertEqual(
'/ns-included1/ns-included4/ns-included1/test3/inner/42/37/',
reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual(
'/ns-included1/ns-included4/ns-included1/test3/inner/+%5C$*/',
reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-special-view')
)
def test_app_lookup_object(self):
"A default application namespace can be used for lookup"
self.assertEqual('/default/inner/', reverse('testapp:urlobject-view'))
self.assertEqual('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37, 42]))
self.assertEqual('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/default/inner/+%5C$*/', reverse('testapp:urlobject-special-view'))
def test_app_lookup_object_with_default(self):
"A default application namespace is sensitive to the 'current' app can be used for lookup"
self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3'))
self.assertEqual(
'/included/test3/inner/37/42/',
reverse('testapp:urlobject-view', args=[37, 42], current_app='test-ns3')
)
self.assertEqual(
'/included/test3/inner/42/37/',
reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='test-ns3')
)
self.assertEqual(
'/included/test3/inner/+%5C$*/', reverse('testapp:urlobject-special-view', current_app='test-ns3')
)
def test_app_lookup_object_without_default(self):
"An application namespace without a default is sensitive to the 'current' app can be used for lookup"
self.assertEqual('/other2/inner/', reverse('nodefault:urlobject-view'))
self.assertEqual('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42]))
self.assertEqual('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/other2/inner/+%5C$*/', reverse('nodefault:urlobject-special-view'))
self.assertEqual('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1'))
self.assertEqual(
'/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42], current_app='other-ns1')
)
self.assertEqual(
'/other1/inner/42/37/',
reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='other-ns1')
)
self.assertEqual('/other1/inner/+%5C$*/', reverse('nodefault:urlobject-special-view', current_app='other-ns1'))
def test_special_chars_namespace(self):
self.assertEqual('/+%5C$*/included/normal/', reverse('special:inc-normal-view'))
self.assertEqual('/+%5C$*/included/normal/37/42/', reverse('special:inc-normal-view', args=[37, 42]))
self.assertEqual(
'/+%5C$*/included/normal/42/37/',
reverse('special:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/+%5C$*/included/+%5C$*/', reverse('special:inc-special-view'))
def test_namespaces_with_variables(self):
"Namespace prefixes can capture variables: see #15900"
self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', kwargs={'outer': '70'}))
self.assertEqual(
'/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', kwargs={'outer': '78', 'extra': 'foobar'})
)
self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', args=['70']))
self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', args=['78', 'foobar']))
def test_nested_app_lookup(self):
"A nested current_app should be split in individual namespaces (#24904)"
self.assertEqual('/ns-included1/test4/inner/', reverse('inc-ns1:testapp:urlobject-view'))
self.assertEqual('/ns-included1/test4/inner/37/42/', reverse('inc-ns1:testapp:urlobject-view', args=[37, 42]))
self.assertEqual(
'/ns-included1/test4/inner/42/37/',
reverse('inc-ns1:testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
)
self.assertEqual('/ns-included1/test4/inner/+%5C$*/', reverse('inc-ns1:testapp:urlobject-special-view'))
self.assertEqual(
'/ns-included1/test3/inner/',
reverse('inc-ns1:testapp:urlobject-view', current_app='inc-ns1:test-ns3')
)
self.assertEqual(
'/ns-included1/test3/inner/37/42/',
reverse('inc-ns1:testapp:urlobject-view', args=[37, 42], current_app='inc-ns1:test-ns3')
)
self.assertEqual(
'/ns-included1/test3/inner/42/37/',
reverse('inc-ns1:testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='inc-ns1:test-ns3')
)
self.assertEqual(
'/ns-included1/test3/inner/+%5C$*/',
reverse('inc-ns1:testapp:urlobject-special-view', current_app='inc-ns1:test-ns3')
)
def test_current_app_no_partial_match(self):
"current_app should either match the whole path or shouldn't be used"
self.assertEqual(
'/ns-included1/test4/inner/',
reverse('inc-ns1:testapp:urlobject-view', current_app='non-existent:test-ns3')
)
self.assertEqual(
'/ns-included1/test4/inner/37/42/',
reverse('inc-ns1:testapp:urlobject-view', args=[37, 42], current_app='non-existent:test-ns3')
)
self.assertEqual(
'/ns-included1/test4/inner/42/37/',
reverse('inc-ns1:testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37},
current_app='non-existent:test-ns3')
)
self.assertEqual(
'/ns-included1/test4/inner/+%5C$*/',
reverse('inc-ns1:testapp:urlobject-special-view', current_app='non-existent:test-ns3')
)
@override_settings(ROOT_URLCONF=urlconf_outer.__name__)
class RequestURLconfTests(SimpleTestCase):
def test_urlconf(self):
response = self.client.get('/test/me/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'outer:/test/me/,inner:/inner_urlconf/second_test/')
response = self.client.get('/inner_urlconf/second_test/')
self.assertEqual(response.status_code, 200)
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 404)
@override_settings(
MIDDLEWARE=[
'%s.ChangeURLconfMiddleware' % middleware.__name__,
]
)
def test_urlconf_overridden(self):
response = self.client.get('/test/me/')
self.assertEqual(response.status_code, 404)
response = self.client.get('/inner_urlconf/second_test/')
self.assertEqual(response.status_code, 404)
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'outer:,inner:/second_test/')
@override_settings(
MIDDLEWARE=[
'%s.NullChangeURLconfMiddleware' % middleware.__name__,
]
)
def test_urlconf_overridden_with_null(self):
"""
Overriding request.urlconf with None will fall back to the default
URLconf.
"""
response = self.client.get('/test/me/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'outer:/test/me/,inner:/inner_urlconf/second_test/')
response = self.client.get('/inner_urlconf/second_test/')
self.assertEqual(response.status_code, 200)
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 404)
@override_settings(
MIDDLEWARE=[
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseInnerInResponseMiddleware' % middleware.__name__,
]
)
def test_reverse_inner_in_response_middleware(self):
"""
Test reversing an URL from the *overridden* URLconf from inside
a response middleware.
"""
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'/second_test/')
@override_settings(
MIDDLEWARE=[
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseOuterInResponseMiddleware' % middleware.__name__,
]
)
def test_reverse_outer_in_response_middleware(self):
"""
Test reversing an URL from the *default* URLconf from inside
a response middleware.
"""
message = "Reverse for 'outer' with arguments '()' and keyword arguments '{}' not found."
with self.assertRaisesMessage(NoReverseMatch, message):
self.client.get('/second_test/')
@override_settings(
MIDDLEWARE=[
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseInnerInStreaming' % middleware.__name__,
]
)
def test_reverse_inner_in_streaming(self):
"""
Test reversing an URL from the *overridden* URLconf from inside
a streaming response.
"""
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 200)
self.assertEqual(b''.join(response), b'/second_test/')
@override_settings(
MIDDLEWARE=[
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseOuterInStreaming' % middleware.__name__,
]
)
def test_reverse_outer_in_streaming(self):
"""
Test reversing an URL from the *default* URLconf from inside
a streaming response.
"""
message = "Reverse for 'outer' with arguments '()' and keyword arguments '{}' not found."
with self.assertRaisesMessage(NoReverseMatch, message):
self.client.get('/second_test/')
b''.join(self.client.get('/second_test/'))
class ErrorHandlerResolutionTests(SimpleTestCase):
"""Tests for handler400, handler404 and handler500"""
def setUp(self):
urlconf = 'urlpatterns_reverse.urls_error_handlers'
urlconf_callables = 'urlpatterns_reverse.urls_error_handlers_callables'
self.resolver = RegexURLResolver(r'^$', urlconf)
self.callable_resolver = RegexURLResolver(r'^$', urlconf_callables)
def test_named_handlers(self):
handler = (empty_view, {})
self.assertEqual(self.resolver.resolve_error_handler(400), handler)
self.assertEqual(self.resolver.resolve_error_handler(404), handler)
self.assertEqual(self.resolver.resolve_error_handler(500), handler)
def test_callable_handlers(self):
handler = (empty_view, {})
self.assertEqual(self.callable_resolver.resolve_error_handler(400), handler)
self.assertEqual(self.callable_resolver.resolve_error_handler(404), handler)
self.assertEqual(self.callable_resolver.resolve_error_handler(500), handler)
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls_without_full_import')
class DefaultErrorHandlerTests(SimpleTestCase):
def test_default_handler(self):
"If the urls.py doesn't specify handlers, the defaults are used"
response = self.client.get('/test/')
self.assertEqual(response.status_code, 404)
with self.assertRaisesMessage(ValueError, "I don't think I'm getting good"):
self.client.get('/bad_view/')
@override_settings(ROOT_URLCONF=None)
class NoRootUrlConfTests(SimpleTestCase):
"""Tests for handler404 and handler500 if ROOT_URLCONF is None"""
def test_no_handler_exception(self):
with self.assertRaises(ImproperlyConfigured):
self.client.get('/test/me/')
@override_settings(ROOT_URLCONF='urlpatterns_reverse.namespace_urls')
class ResolverMatchTests(SimpleTestCase):
@ignore_warnings(category=RemovedInDjango20Warning)
def test_urlpattern_resolve(self):
for path, url_name, app_name, namespace, view_name, func, args, kwargs in resolve_test_data:
# Test legacy support for extracting "function, args, kwargs"
match_func, match_args, match_kwargs = resolve(path)
self.assertEqual(match_func, func)
self.assertEqual(match_args, args)
self.assertEqual(match_kwargs, kwargs)
# Test ResolverMatch capabilities.
match = resolve(path)
self.assertEqual(match.__class__, ResolverMatch)
self.assertEqual(match.url_name, url_name)
self.assertEqual(match.app_name, app_name)
self.assertEqual(match.namespace, namespace)
self.assertEqual(match.view_name, view_name)
self.assertEqual(match.func, func)
self.assertEqual(match.args, args)
self.assertEqual(match.kwargs, kwargs)
# ... and for legacy purposes:
self.assertEqual(match[0], func)
self.assertEqual(match[1], args)
self.assertEqual(match[2], kwargs)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_resolver_match_on_request(self):
response = self.client.get('/resolver_match/')
resolver_match = response.resolver_match
self.assertEqual(resolver_match.url_name, 'test-resolver-match')
def test_resolver_match_on_request_before_resolution(self):
request = HttpRequest()
self.assertIsNone(request.resolver_match)
@override_settings(ROOT_URLCONF='urlpatterns_reverse.erroneous_urls')
class ErroneousViewTests(SimpleTestCase):
def test_noncallable_view(self):
# View is not a callable (explicit import; arbitrary Python object)
with self.assertRaisesMessage(TypeError, 'view must be a callable'):
url(r'uncallable-object/$', views.uncallable)
def test_invalid_regex(self):
# Regex contains an error (refs #6170)
msg = '(regex_error/$" is not a valid regular expression'
with self.assertRaisesMessage(ImproperlyConfigured, msg):
reverse(views.empty_view)
class ViewLoadingTests(SimpleTestCase):
def test_view_loading(self):
self.assertEqual(get_callable('urlpatterns_reverse.views.empty_view'), empty_view)
# passing a callable should return the callable
self.assertEqual(get_callable(empty_view), empty_view)
def test_exceptions(self):
# A missing view (identified by an AttributeError) should raise
# ViewDoesNotExist, ...
with self.assertRaisesMessage(ViewDoesNotExist, "View does not exist in"):
get_callable('urlpatterns_reverse.views.i_should_not_exist')
# ... but if the AttributeError is caused by something else don't
# swallow it.
with self.assertRaises(AttributeError):
get_callable('urlpatterns_reverse.views_broken.i_am_broken')
class IncludeTests(SimpleTestCase):
url_patterns = [
url(r'^inner/$', views.empty_view, name='urlobject-view'),
url(r'^inner/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.empty_view, name='urlobject-view'),
url(r'^inner/\+\\\$\*/$', views.empty_view, name='urlobject-special-view'),
]
app_urls = URLObject('inc-app')
def test_include_app_name_but_no_namespace(self):
msg = "Must specify a namespace if specifying app_name."
with self.assertRaisesMessage(ValueError, msg):
include(self.url_patterns, app_name='bar')
def test_include_urls(self):
self.assertEqual(include(self.url_patterns), (self.url_patterns, None, None))
@ignore_warnings(category=RemovedInDjango20Warning)
def test_include_namespace(self):
# no app_name -> deprecated
self.assertEqual(include(self.url_patterns, 'namespace'), (self.url_patterns, None, 'namespace'))
@ignore_warnings(category=RemovedInDjango20Warning)
def test_include_namespace_app_name(self):
# app_name argument to include -> deprecated
self.assertEqual(
include(self.url_patterns, 'namespace', 'app_name'),
(self.url_patterns, 'app_name', 'namespace')
)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_include_3_tuple(self):
# 3-tuple -> deprecated
self.assertEqual(
include((self.url_patterns, 'app_name', 'namespace')),
(self.url_patterns, 'app_name', 'namespace')
)
def test_include_2_tuple(self):
self.assertEqual(
include((self.url_patterns, 'app_name')),
(self.url_patterns, 'app_name', 'app_name')
)
def test_include_2_tuple_namespace(self):
self.assertEqual(
include((self.url_patterns, 'app_name'), namespace='namespace'),
(self.url_patterns, 'app_name', 'namespace')
)
def test_include_app_name(self):
self.assertEqual(
include(self.app_urls),
(self.app_urls, 'inc-app', 'inc-app')
)
def test_include_app_name_namespace(self):
self.assertEqual(
include(self.app_urls, 'namespace'),
(self.app_urls, 'inc-app', 'namespace')
)
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')
class LookaheadTests(SimpleTestCase):
def test_valid_resolve(self):
test_urls = [
'/lookahead-/a-city/',
'/lookbehind-/a-city/',
'/lookahead+/a-city/',
'/lookbehind+/a-city/',
]
for test_url in test_urls:
match = resolve(test_url)
self.assertEqual(match.kwargs, {'city': 'a-city'})
def test_invalid_resolve(self):
test_urls = [
'/lookahead-/not-a-city/',
'/lookbehind-/not-a-city/',
'/lookahead+/other-city/',
'/lookbehind+/other-city/',
]
for test_url in test_urls:
with self.assertRaises(Resolver404):
resolve(test_url)
def test_valid_reverse(self):
url = reverse('lookahead-positive', kwargs={'city': 'a-city'})
self.assertEqual(url, '/lookahead+/a-city/')
url = reverse('lookahead-negative', kwargs={'city': 'a-city'})
self.assertEqual(url, '/lookahead-/a-city/')
url = reverse('lookbehind-positive', kwargs={'city': 'a-city'})
self.assertEqual(url, '/lookbehind+/a-city/')
url = reverse('lookbehind-negative', kwargs={'city': 'a-city'})
self.assertEqual(url, '/lookbehind-/a-city/')
def test_invalid_reverse(self):
with self.assertRaises(NoReverseMatch):
reverse('lookahead-positive', kwargs={'city': 'other-city'})
with self.assertRaises(NoReverseMatch):
reverse('lookahead-negative', kwargs={'city': 'not-a-city'})
with self.assertRaises(NoReverseMatch):
reverse('lookbehind-positive', kwargs={'city': 'other-city'})
with self.assertRaises(NoReverseMatch):
reverse('lookbehind-negative', kwargs={'city': 'not-a-city'})<|fim▁end|> | with self.assertRaises(NoReverseMatch):
reverse('test-ns1:blahblah:urlobject-view')
def test_normal_name(self): |
<|file_name|>libyaLow.js<|end_file_name|><|fim▁begin|>// (c) ammap.com | SVG (in JSON format) map of Libya - Low
// areas: {id:"LY-WD"},{id:"LY-BU"},{id:"LY-DR"},{id:"LY-SR"},{id:"LY-BA"},{id:"LY-WA"},{id:"LY-JA"},{id:"LY-HZ"},{id:"LY-TB"},{id:"LY-MZ"},{id:"LY-ZA"},{id:"LY-NQ"},{id:"LY-JI"},{id:"LY-SB"},{id:"LY-MI"},{id:"LY-MQ"},{id:"LY-GT"},{id:"LY-WS"},{id:"LY-MB"},{id:"LY-KF"},{id:"LY-JU"},{id:"LY-NL"}
AmCharts.maps.libyaLow={
"svg": {
"defs": {
"amcharts:ammap": {
"projection":"mercator",
"leftLongitude":"9.391466",
"topLatitude":"33.1679793",
"rightLongitude":"25.146954",
"bottomLatitude":"19.5008125"
}
},
"g":{
"path":[
{
"id":"LY-WD",
"title":"Wadi al Hayaa",
"d":"M236.97,352.67L188.1,345.8L105.65,404.02L106.9,441.29L145.18,439.93L234.51,402.37L245.18,378.51L236.97,352.67z"
},
{
"id":"LY-BU",
"title":"Al Butnan",
"d":"M790.67,297.68L790.32,232.14L775.94,177.43L791.36,142.24L784.01,109.12L799.48,90.55L790.69,72.49L703.58,57.71L689.36,141.4L694.05,295.25L790.67,297.68z"
},
{
"id":"LY-DR",
"title":"Darnah",
"d":"M703.58,57.71L696.27,32.47L639.88,16.11L636.44,113.04L646.24,122.59L689.36,141.4L703.58,57.71z"
},
{
"id":"LY-SR",
"title":"Surt",
"d":"M478.97,166.48L407.27,124.54L345.42,114.27L365.25,209.36L359.58,222.33L405.66,229.62L418.06,223.15L438.3,261.26L464.33,274.5L478.97,166.48z"
},
{
"id":"LY-BA",
"title":"Benghazi",
"d":"M606.3,127.57L601.08,97.76L567.51,95.48L557.53,74.82L568.89,37.08L536.87,73.09L547.02,116.47L569.78,129.22L606.3,127.57z"
},
{
"id":"LY-WA",
"title":"Al Wahat",
"d":"M606.3,127.57L569.78,129.22L547.02,116.47L541.73,140.25L520.58,163.52L496.89,172.65L478.97,166.48L464.33,274.5L498.21,283.36L498.09,359.23L790.67,357.18L790.67,297.68L694.05,295.25L689.36,141.4L646.24,122.59L626.34,125.78L606.3,127.57z"
},
{
"id":"LY-JA",
"title":"Al Jabal al Akhdar",
"d":"M639.88,16.11L608.21,24.06L626.34,125.78L646.24,122.59L636.44,113.04L639.88,16.11z"
},
{
"id":"LY-MJ",
"title":"Al Marj",
"d":"M608.21,24.06L568.89,37.08L557.53,74.82L567.51,95.48L601.08,97.76L606.3,127.57L626.34,125.78L608.21,24.06z"
},
{
"id":"LY-TB",
"title":"Tripoli",
"d":"M235.52,25.39L192.67,18.24L191.32,27.6L199.38,50.74L235.52,25.39z"
},
{
"id":"LY-JG",
"title":"Al Jabal al Gharbi",
"d":"M207.49,67.57L200.1,51.71L178.39,55.12L130.21,52.3L135.27,124.88L116.48,156.44L123.5,240.9L134.7,269.17L171.79,278.61L233.31,213.15L258.95,233.86L275.7,222.53L280.82,196.08L285.65,164.23L248.47,145.99L207.49,67.57z"
},
{
"id":"LY-ZA",
"title":"Az Zawiyah",
"d":"M191.32,27.6L192.67,18.24L165.98,22.13L130.21,52.3L178.39,55.12L191.32,27.6z"
},
{
"id":"LY-NQ",
"title":"An Nuqat al Khams",
"d":"M112.21,0L113.27,45.72L130.21,52.3L165.98,22.13L112.21,0z"
},
{
"id":"LY-JI",
"title":"Al Jifarah",
"d":"M199.38,50.74L191.32,27.6L178.39,55.12L200.1,51.71L199.38,50.74z"
},
{
"id":"LY-SB",
"title":"Sabha",
"d":"M328.23,319.08L291.61,324.15L259.02,350.19L236.97,352.67L245.18,378.51L234.51,402.37L259.18,395.1L279.48,373.62L352.59,355.71L328.23,319.08z"
},
{
"id":"LY-MI",
"title":"Misratah",
"d":"M345.42,114.27L314.06,92.6L301.74,51.03L275.87,43.83L271.38,72.5L243.96,62.12L207.49,67.57L248.47,145.99L285.65,164.23L280.82,196.08L325.45,223.19L359.58,222.33L365.25,209.36L345.42,114.27z"
},
{
"id":"LY-MQ",
"title":"Murzuq",
"d":"M498,416L449.47,395.09L409.49,413.29L385.86,407.05L352.53,368.64L352.59,355.71L279.48,373.62L259.18,395.1L234.51,402.37L145.18,439.93L106.9,441.29L110.31,509.32L135.56,553.87L211.75,572.39L248.7,603.18L337.76,557.86L498.9,644.09L498,416z"
},
{
"id":"LY-GT",
"title":"Ghat",
"d":"M105.65,404.02L92.16,335.26L32.98,313.53L22.41,343.44L31.22,379.55L6.29,409.86L36.84,453.56L38.05,479.97L49.54,495.47L110.31,509.32L106.9,441.29L105.65,404.02z"
},
{
"id":"LY-WS",
"title":"Wadi ash Shati'",
"d":"M258.95,233.86L233.31,213.15L171.79,278.61L134.7,269.17L103.09,272.05L82.24,254.85L58.63,267.48L27.74,267.82L32.98,313.53L92.16,335.26L105.65,404.02L188.1,345.8L236.97,352.67L259.02,350.19L291.61,324.15L328.23,319.08L332.41,298.68L317.85,290.94L289.05,294.93L286.08,279.91L259.09,252.9L258.95,233.86z"
},
{
"id":"LY-MB",
"title":"Al Marqab",
"d":"M275.87,43.83L235.52,25.39L199.38,50.74L200.1,51.71L207.49,67.57L243.96,62.12L271.38,72.5L275.87,43.83z"
},
{
"id":"LY-KF",
"title":"Al Kufrah",
"d":"M740.33,771.53L740.33,744.82L790.45,744.79L790.67,357.18L498.09,359.23L498,416L498.9,644.09L740.33,771.53z"
},
{
"id":"LY-JU",
"title":"Al Jufrah",
"d":"M359.58,222.33L325.45,223.19L280.82,196.08L275.7,222.53L258.95,233.86L259.09,252.9L286.08,279.91L289.05,294.93L317.85,290.94L332.41,298.68L328.23,319.08L352.59,355.71L352.53,368.64L385.86,407.05L409.49,413.29L449.47,395.09L498,416L498.09,359.23L498.21,283.36L464.33,274.5L438.3,261.26L418.06,223.15L405.66,229.62L359.58,222.33z"
},
{
"id":"LY-NL",
"title":"Nalut",<|fim▁hole|> }
]
}
}
};<|fim▁end|> | "d":"M130.21,52.3L113.27,45.72L49.73,89.52L41.79,104.37L46.11,145.4L29.96,167.38L0.52,181.25L19.71,210.79L27.74,267.82L58.63,267.48L82.24,254.85L103.09,272.05L134.7,269.17L123.5,240.9L116.48,156.44L135.27,124.88L130.21,52.3z" |
<|file_name|>issue-980.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//<|fim▁hole|>// except according to those terms.
use std::cell::RefCell;
use std::gc::{Gc, GC};
enum maybe_pointy {
no_pointy,
yes_pointy(Gc<RefCell<Pointy>>),
}
struct Pointy {
x: maybe_pointy
}
pub fn main() {
let m = box(GC) RefCell::new(Pointy { x : no_pointy });
*m.borrow_mut() = Pointy {
x: yes_pointy(m)
};
}<|fim▁end|> | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed |
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::lexer::TokenKind;
use crate::node::*;
use crate::syntax_error::SyntaxError;
use common::{Diagnostic, DiagnosticsResult, Location, SourceLocationKey, Span, WithDiagnostics};
use interner::Intern;
use logos::Logos;
type ParseResult<T> = Result<T, ()>;
#[derive(Default)]
pub struct ParserFeatures {
/// Enable the experimental fragment variables definitions syntax
pub enable_variable_definitions: bool,
}
pub struct Parser<'a> {
current: Token,
features: ParserFeatures,
lexer: logos::Lexer<'a, TokenKind>,
errors: Vec<Diagnostic>,
source_location: SourceLocationKey,
source: &'a str,
/// the byte offset of the *end* of the previous token
end_index: u32,
}
/// Parser for the *executable* subset of the GraphQL specification:
/// https://github.com/graphql/graphql-spec/blob/master/spec/Appendix%20B%20--%20Grammar%20Summary.md
impl<'a> Parser<'a> {
pub fn new(
source: &'a str,
source_location: SourceLocationKey,
features: ParserFeatures,
) -> Self {
// To enable fast lookahead the parser needs to store at least the 'kind' (TokenKind)
// of the next token: the simplest option is to store the full current token, but
// the Parser requires an initial value. Rather than incur runtime/code overhead
// of dealing with an Option or UnsafeCell, the constructor uses a dummy token
// value to construct the Parser, then immediately advance()s to move to the
// first real token.
let lexer = TokenKind::lexer(source);
let dummy = Token {
kind: TokenKind::EndOfFile,
span: Span::empty(),
};
let mut parser = Parser {
current: dummy,
errors: Vec::new(),
features,
lexer,
source_location,
source,
end_index: 0,
};
// Advance to the first real token before doing any work
parser.parse_token();
parser
}
pub fn parse_document(mut self) -> DiagnosticsResult<Document> {
let document = self.parse_document_impl();
if self.errors.is_empty() {
self.parse_eof()?;
Ok(document.unwrap())
} else {
Err(self.errors)
}
}
/// Parses a string containing a single directive.
pub fn parse_directive(mut self) -> DiagnosticsResult<Directive> {
let document = self.parse_directive_impl();
if self.errors.is_empty() {
self.parse_eof()?;
Ok(document.unwrap())
} else {
Err(self.errors)
}
}
/// Parses a document consisting only of executable nodes: operations and
/// fragments.
pub fn parse_executable_document(mut self) -> WithDiagnostics<ExecutableDocument> {
let document = self.parse_executable_document_impl();
if self.errors.is_empty() {
let _ = self.parse_kind(TokenKind::EndOfFile);
}
let document = document.unwrap_or_else(|_| ExecutableDocument {
span: Span::new(0, 0),
definitions: Default::default(),
});
WithDiagnostics {
item: document,
errors: self.errors,
}
}
pub fn parse_schema_document(mut self) -> DiagnosticsResult<SchemaDocument> {
let document = self.parse_schema_document_impl();
if self.errors.is_empty() {
self.parse_eof()?;
Ok(document.unwrap())
} else {
Err(self.errors)
}
}
/// Parses a type annotation such as `ID` or `[User!]!`.
pub fn parse_type(mut self) -> DiagnosticsResult<TypeAnnotation> {
let type_annotation = self.parse_type_annotation();
if self.errors.is_empty() {
self.parse_eof()?;
Ok(type_annotation.unwrap())
} else {
Err(self.errors)
}
}
fn parse_eof(mut self) -> DiagnosticsResult<()> {
self.parse_kind(TokenKind::EndOfFile)
.map(|_| ())
.map_err(|_| self.errors)
}
// Document / Definitions
/// Document : Definition+
fn parse_document_impl(&mut self) -> ParseResult<Document> {
let start = self.index();
let definitions = self.parse_list(|s| s.peek_definition(), |s| s.parse_definition())?;
let end = self.index();
let span = Span::new(start, end);
Ok(Document {
location: Location::new(self.source_location, span),
definitions,
})
}
fn parse_executable_document_impl(&mut self) -> ParseResult<ExecutableDocument> {
let start = self.index();
let definitions = self.parse_list(
|s| s.peek_executable_definition(),
|s| s.parse_executable_definition(),
)?;
let end = self.index();
let span = Span::new(start, end);
Ok(ExecutableDocument { span, definitions })
}
fn parse_schema_document_impl(&mut self) -> ParseResult<SchemaDocument> {
let start = self.index();
let definitions = self.parse_list(
|s| s.peek_type_system_definition(),
|s| s.parse_type_system_definition(),
)?;
let end = self.index();
let span = Span::new(start, end);
Ok(SchemaDocument {
location: Location::new(self.source_location, span),
definitions,
})
}
/// Definition :
/// [x] ExecutableDefinition
/// [x] TypeSystemDefinition
/// [x] TypeSystemExtension
fn peek_definition(&self) -> bool {
self.peek_executable_definition() || self.peek_type_system_definition()
}
fn parse_definition(&mut self) -> ParseResult<Definition> {
let token = self.peek();
let source = self.source(&token);
match (token.kind, source) {
(TokenKind::OpenBrace, _)
| (TokenKind::Identifier, "query")
| (TokenKind::Identifier, "mutation")
| (TokenKind::Identifier, "subscription")
| (TokenKind::Identifier, "fragment") => Ok(Definition::ExecutableDefinition(
self.parse_executable_definition()?,
)),
(TokenKind::StringLiteral, _)
| (TokenKind::BlockStringLiteral, _)
| (TokenKind::Identifier, "schema")
| (TokenKind::Identifier, "scalar")
| (TokenKind::Identifier, "type")
| (TokenKind::Identifier, "interface")
| (TokenKind::Identifier, "union")
| (TokenKind::Identifier, "enum")
| (TokenKind::Identifier, "input")
| (TokenKind::Identifier, "directive")
| (TokenKind::Identifier, "extend") => Ok(Definition::TypeSystemDefinition(
self.parse_type_system_definition()?,
)),
_ => {
let error = Diagnostic::error(
SyntaxError::ExpectedDefinition,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/// Definition :
/// [x] ExecutableDefinition
/// [] TypeSystemDefinition
/// [] TypeSystemExtension
fn peek_executable_definition(&self) -> bool {
let token = self.peek();
match token.kind {
TokenKind::OpenBrace => true, // unnamed query
TokenKind::Identifier => matches!(
self.source(&token),
"query" | "mutation" | "fragment" | "subscription"
),
_ => false,
}
}
/// Definition :
/// [x] ExecutableDefinition
/// [] TypeSystemDefinition
/// [] TypeSystemExtension
fn parse_executable_definition(&mut self) -> ParseResult<ExecutableDefinition> {
let token = self.peek();
let source = self.source(&token);
match (token.kind, source) {
(TokenKind::OpenBrace, _) => Ok(ExecutableDefinition::Operation(
self.parse_operation_definition()?,
)),
(TokenKind::Identifier, "query")
| (TokenKind::Identifier, "mutation")
| (TokenKind::Identifier, "subscription") => Ok(ExecutableDefinition::Operation(
self.parse_operation_definition()?,
)),
(TokenKind::Identifier, "fragment") => Ok(ExecutableDefinition::Fragment(
self.parse_fragment_definition()?,
)),
_ => {
let error = Diagnostic::error(
SyntaxError::ExpectedExecutableDefinition,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/// Definition :
/// [] ExecutableDefinition
/// [x] TypeSystemDefinition
/// [] TypeSystemExtension
fn peek_type_system_definition(&self) -> bool {
let token = self.peek();
match token.kind {
TokenKind::StringLiteral | TokenKind::BlockStringLiteral => true, // description
TokenKind::Identifier => matches!(
self.source(&token),
"schema"
| "scalar"
| "type"
| "interface"
| "union"
| "enum"
| "input"
| "directive"
| "extend"
),
_ => false,
}
}
/// Definition :
/// [] ExecutableDefinition
/// [x] TypeSystemDefinition
/// [] TypeSystemExtension
fn parse_type_system_definition(&mut self) -> ParseResult<TypeSystemDefinition> {
self.parse_optional_description();
let token = self.peek();
if token.kind != TokenKind::Identifier {
// TODO
// self.record_error(error)
return Err(());
}
match self.source(&token) {
"schema" => Ok(TypeSystemDefinition::SchemaDefinition(
self.parse_schema_definition()?,
)),
"scalar" => Ok(TypeSystemDefinition::ScalarTypeDefinition(
self.parse_scalar_type_definition()?,
)),
"type" => Ok(TypeSystemDefinition::ObjectTypeDefinition(
self.parse_object_type_definition()?,
)),
"interface" => Ok(TypeSystemDefinition::InterfaceTypeDefinition(
self.parse_interface_type_definition()?,
)),
"union" => Ok(TypeSystemDefinition::UnionTypeDefinition(
self.parse_union_type_definition()?,
)),
"enum" => Ok(TypeSystemDefinition::EnumTypeDefinition(
self.parse_enum_type_definition()?,
)),
"input" => Ok(TypeSystemDefinition::InputObjectTypeDefinition(
self.parse_input_object_type_definition()?,
)),
"directive" => Ok(TypeSystemDefinition::DirectiveDefinition(
self.parse_directive_definition()?,
)),
"extend" => self.parse_type_system_extension(),
token_str => {
let error = Diagnostic::error(
format!("Unexpected token: `{}`", token_str),
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/**
* TypeSystemExtension :
* - SchemaExtension
* - TypeExtension
*
* TypeExtension :
* - ScalarTypeExtension
* - ObjectTypeExtension
* - InterfaceTypeExtension
* - UnionTypeExtension
* - EnumTypeExtension
* - InputObjectTypeDefinition
*/
pub fn parse_type_system_extension(&mut self) -> ParseResult<TypeSystemDefinition> {
self.parse_keyword("extend")?;
let token = self.parse_kind(TokenKind::Identifier)?;
match self.source(&token) {
"schema" => Ok(TypeSystemDefinition::SchemaExtension(
self.parse_schema_extension()?,
)),
"scalar" => Ok(TypeSystemDefinition::ScalarTypeExtension(
self.parse_scalar_type_extension()?,
)),
"type" => Ok(TypeSystemDefinition::ObjectTypeExtension(
self.parse_object_type_extension()?,
)),
"interface" => Ok(TypeSystemDefinition::InterfaceTypeExtension(
self.parse_interface_type_extension()?,
)),
"union" => Ok(TypeSystemDefinition::UnionTypeExtension(
self.parse_union_type_extension()?,
)),
"enum" => Ok(TypeSystemDefinition::EnumTypeExtension(
self.parse_enum_type_extension()?,
)),
"input" => Ok(TypeSystemDefinition::InputObjectTypeExtension(
self.parse_input_object_type_extension()?,
)),
token_str => {
let error = Diagnostic::error(
format!("Unexpected token `{}`", token_str),
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/**
* SchemaDefinition : schema Directives? { OperationTypeDefinition+ }
*/
fn parse_schema_definition(&mut self) -> ParseResult<SchemaDefinition> {
self.parse_keyword("schema")?;
let directives = self.parse_constant_directives()?;
let operation_types = self.parse_delimited_nonempty_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
Self::parse_operation_type_definition,
)?;
Ok(SchemaDefinition {
directives,
operation_types,
})
}
/**
* SchemaExtension :
* - extend schema Directives? { OperationTypeDefinition+ }
* - extend schema Directives
*/
fn parse_schema_extension(&mut self) -> ParseResult<SchemaExtension> {
// `extend schema` was already parsed
let directives = self.parse_constant_directives()?;
let operation_types = self.parse_optional_delimited_nonempty_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
Self::parse_operation_type_definition,
)?;
Ok(SchemaExtension {
directives,
operation_types,
})
}
/**
* OperationTypeDefinition : OperationType : NamedType
*/
fn parse_operation_type_definition(&mut self) -> ParseResult<OperationTypeDefinition> {
let operation = self.parse_operation_type()?;
self.parse_kind(TokenKind::Colon)?;
let type_ = self.parse_identifier()?;
Ok(OperationTypeDefinition { operation, type_ })
}
/**
* OperationType : one of query mutation subscription
*/
fn parse_operation_type(&mut self) -> ParseResult<OperationType> {
let token = self.parse_kind(TokenKind::Identifier)?;
match self.source(&token) {
"query" => Ok(OperationType::Query),
"mutation" => Ok(OperationType::Mutation),
"subscription" => Ok(OperationType::Subscription),
token_str => {
let error = Diagnostic::error(
format!(
"Expected one of `query`, `mutation`, `subscription`, got `{}`",
token_str
),
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
fn parse_object_type_definition(&mut self) -> ParseResult<ObjectTypeDefinition> {
self.parse_keyword("type")?;
let name = self.parse_identifier()?;
let interfaces = self.parse_implements_interfaces()?;
let directives = self.parse_constant_directives()?;
let fields = self.parse_fields_definition()?;
Ok(ObjectTypeDefinition {
name,
interfaces,
directives,
fields,
})
}
fn parse_interface_type_definition(&mut self) -> ParseResult<InterfaceTypeDefinition> {
self.parse_keyword("interface")?;
let name = self.parse_identifier()?;
let interfaces = self.parse_implements_interfaces()?;
let directives = self.parse_constant_directives()?;
let fields = self.parse_fields_definition()?;
Ok(InterfaceTypeDefinition {
name,
interfaces,
directives,
fields,
})
}
/**
* UnionTypeDefinition :
* - Description? union Name Directives? UnionMemberTypes?
*/
fn parse_union_type_definition(&mut self) -> ParseResult<UnionTypeDefinition> {
self.parse_keyword("union")?;
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
let members = self.parse_union_member_types()?;
Ok(UnionTypeDefinition {
name,
directives,
members,
})
}
/**
* UnionTypeExtension :
* - extend union Name Directives? UnionMemberTypes
* - extend union Name Directives
*/
fn parse_union_type_extension(&mut self) -> ParseResult<UnionTypeExtension> {
// `extend union` was parsed before
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
let members = self.parse_union_member_types()?;
Ok(UnionTypeExtension {
name,
directives,
members,
})
}
/**
* UnionMemberTypes :
* - = `|`? NamedType
* - UnionMemberTypes | NamedType
*/
fn parse_union_member_types(&mut self) -> ParseResult<Vec<Identifier>> {
let mut members = vec![];
if self.parse_optional_kind(TokenKind::Equals).is_some() {
self.parse_optional_kind(TokenKind::Pipe);
members.push(self.parse_identifier()?);
while self.parse_optional_kind(TokenKind::Pipe).is_some() {
members.push(self.parse_identifier()?);
}
}
Ok(members)
}
/**
* EnumTypeDefinition :
* - Description? enum Name Directives? EnumValuesDefinition?
*/
fn parse_enum_type_definition(&mut self) -> ParseResult<EnumTypeDefinition> {
self.parse_keyword("enum")?;
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
let values = self.parse_enum_values_definition()?;
Ok(EnumTypeDefinition {
name,
directives,
values,
})
}
/**
* EnumTypeExtension :
* - extend enum Name Directives? EnumValuesDefinition
* - extend enum Name Directives
*/
fn parse_enum_type_extension(&mut self) -> ParseResult<EnumTypeExtension> {
// `extend enum` was already parsed
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
let values = self.parse_enum_values_definition()?;
Ok(EnumTypeExtension {
name,
directives,
values,
})
}
/**
* EnumValuesDefinition : { EnumValueDefinition+ }
*/
fn parse_enum_values_definition(&mut self) -> ParseResult<Option<List<EnumValueDefinition>>> {
self.parse_optional_delimited_nonempty_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
Self::parse_enum_value_definition,
)
}
/**
* EnumValueDefinition : Description? EnumValue Directives?
*
* EnumValue : Name
*/
fn parse_enum_value_definition(&mut self) -> ParseResult<EnumValueDefinition> {
self.parse_optional_description();
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
Ok(EnumValueDefinition { name, directives })
}
/**
* ObjectTypeExtension :
* - extend type Name ImplementsInterfaces? DirectivesConst? FieldsDefinition
* - extend type Name ImplementsInterfaces? DirectivesConst
* - extend type Name ImplementsInterfaces
*/
fn parse_object_type_extension(&mut self) -> ParseResult<ObjectTypeExtension> {
// `extend type` was parsed before
let name = self.parse_identifier()?;
let interfaces = self.parse_implements_interfaces()?;
let directives = self.parse_constant_directives()?;
let fields = self.parse_fields_definition()?;
if interfaces.is_empty() && directives.is_empty() && fields.is_none() {
self.record_error(Diagnostic::error(
"Type extension should define one of interfaces, directives or fields.",
Location::new(self.source_location, name.span),
));
return Err(());
}
Ok(ObjectTypeExtension {
name,
fields,
interfaces,
directives,
})
}
/**
* InterfaceTypeExtension :
* - extend interface Name ImplementsInterfaces? DirectivesConst? FieldsDefinition
* - extend interface Name ImplementsInterfaces? DirectivesConst
* - extend interface Name ImplementsInterfaces
*/
fn parse_interface_type_extension(&mut self) -> ParseResult<InterfaceTypeExtension> {
// `extend interface` was parsed before
let name = self.parse_identifier()?;
let interfaces = self.parse_implements_interfaces()?;
let directives = self.parse_constant_directives()?;
let fields = self.parse_fields_definition()?;
if interfaces.is_empty() && directives.is_empty() && fields.is_none() {
self.record_error(Diagnostic::error(
"Interface extension should define one of interfaces, directives or fields.",
Location::new(self.source_location, name.span),
));
return Err(());
}
Ok(InterfaceTypeExtension {
name,
interfaces,
directives,
fields,
})
}
/**
* ScalarTypeDefinition : Description? scalar Name Directives?
*/
fn parse_scalar_type_definition(&mut self) -> ParseResult<ScalarTypeDefinition> {
self.parse_keyword("scalar")?;
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
Ok(ScalarTypeDefinition { name, directives })
}
/**
* ScalarTypeExtension :
* - extend scalar Name Directives
*/
fn parse_scalar_type_extension(&mut self) -> ParseResult<ScalarTypeExtension> {
// `extend scalar` was parsed before
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
Ok(ScalarTypeExtension { name, directives })
}
/**
* InputObjectTypeDefinition :
* - Description? input Name Directives? InputFieldsDefinition?
*/
fn parse_input_object_type_definition(&mut self) -> ParseResult<InputObjectTypeDefinition> {
self.parse_keyword("input")?;
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
let fields = self.parse_input_fields_definition()?;
Ok(InputObjectTypeDefinition {
name,
directives,
fields,
})
}
/**
* InputObjectTypeExtension :
* - extend input Name Directives? InputFieldsDefinition
* - extend input Name Directives
*/
fn parse_input_object_type_extension(&mut self) -> ParseResult<InputObjectTypeExtension> {
// `extend input` was parsed already here
let name = self.parse_identifier()?;
let directives = self.parse_constant_directives()?;
let fields = self.parse_input_fields_definition()?;
Ok(InputObjectTypeExtension {
name,
directives,
fields,
})
}
/**
* InputFieldsDefinition : { InputValueDefinition+ }
*/
fn parse_input_fields_definition(&mut self) -> ParseResult<Option<List<InputValueDefinition>>> {
self.parse_optional_delimited_nonempty_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
Self::parse_input_value_def,
)
}
/**
* DirectiveDefinition :
* - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
*/
fn parse_directive_definition(&mut self) -> ParseResult<DirectiveDefinition> {
self.parse_keyword("directive")?;
self.parse_kind(TokenKind::At)?;
let name = self.parse_identifier()?;
let arguments = self.parse_argument_defs()?;
let repeatable = self.peek_keyword("repeatable");
if repeatable {
self.parse_token();
}
self.parse_keyword("on")?;
let locations = self.parse_directive_locations()?;
Ok(DirectiveDefinition {
name,
arguments,
repeatable,
locations,
})
}
/**
* DirectiveLocations :
* - `|`? DirectiveLocation
* - DirectiveLocations | DirectiveLocation
*/
fn parse_directive_locations(&mut self) -> ParseResult<Vec<DirectiveLocation>> {
let mut locations = Vec::new();
self.parse_optional_kind(TokenKind::Pipe);
locations.push(self.parse_directive_location()?);
while self.parse_optional_kind(TokenKind::Pipe).is_some() {
locations.push(self.parse_directive_location()?);
}
Ok(locations)
}
/*
* DirectiveLocation :
* - ExecutableDirectiveLocation
* - TypeSystemDirectiveLocation
*
* ExecutableDirectiveLocation : one of
* `QUERY`
* `MUTATION`
* `SUBSCRIPTION`
* `FIELD`
* `FRAGMENT_DEFINITION`
* `FRAGMENT_SPREAD`
* `INLINE_FRAGMENT`
*
* TypeSystemDirectiveLocation : one of
* `SCHEMA`
* `SCALAR`
* `OBJECT`
* `FIELD_DEFINITION`
* `ARGUMENT_DEFINITION`
* `INTERFACE`
* `UNION`
* `ENUM`
* `ENUM_VALUE`
* `INPUT_OBJECT`
* `INPUT_FIELD_DEFINITION`
*/
fn parse_directive_location(&mut self) -> ParseResult<DirectiveLocation> {
let token = self.parse_kind(TokenKind::Identifier)?;
match self.source(&token) {
"QUERY" => Ok(DirectiveLocation::Query),
"MUTATION" => Ok(DirectiveLocation::Mutation),
"SUBSCRIPTION" => Ok(DirectiveLocation::Subscription),
"FIELD" => Ok(DirectiveLocation::Field),
"FRAGMENT_DEFINITION" => Ok(DirectiveLocation::FragmentDefinition),
"FRAGMENT_SPREAD" => Ok(DirectiveLocation::FragmentSpread),
"INLINE_FRAGMENT" => Ok(DirectiveLocation::InlineFragment),
"SCHEMA" => Ok(DirectiveLocation::Schema),
"SCALAR" => Ok(DirectiveLocation::Scalar),
"OBJECT" => Ok(DirectiveLocation::Object),
"FIELD_DEFINITION" => Ok(DirectiveLocation::FieldDefinition),
"ARGUMENT_DEFINITION" => Ok(DirectiveLocation::ArgumentDefinition),
"INTERFACE" => Ok(DirectiveLocation::Interface),
"UNION" => Ok(DirectiveLocation::Union),
"ENUM" => Ok(DirectiveLocation::Enum),
"ENUM_VALUE" => Ok(DirectiveLocation::EnumValue),
"INPUT_OBJECT" => Ok(DirectiveLocation::InputObject),
"INPUT_FIELD_DEFINITION" => Ok(DirectiveLocation::InputFieldDefinition),
"VARIABLE_DEFINITION" => Ok(DirectiveLocation::VariableDefinition),
token_str => {
let error = Diagnostic::error(
format!("Unexpected `{}`, expected a directive location.", token_str),
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/**
* Description : StringValue
*/
fn parse_optional_description(&mut self) {
// TODO actually return the description
match self.peek_token_kind() {
TokenKind::StringLiteral | TokenKind::BlockStringLiteral => {
self.parse_token();
}
_ => {}
}
}
/**
* FieldsDefinition : { FieldDefinition+ }
*/
fn parse_fields_definition(&mut self) -> ParseResult<Option<List<FieldDefinition>>> {
self.parse_optional_delimited_nonempty_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
Self::parse_field_definition,
)
}
/**
* FieldDefinition :
* - Description? Name ArgumentsDefinition? : Type Directives?
*/
fn parse_field_definition(&mut self) -> ParseResult<FieldDefinition> {
self.parse_optional_description();
let name = self.parse_identifier()?;
let arguments = self.parse_argument_defs()?;
self.parse_kind(TokenKind::Colon)?;
let type_ = self.parse_type_annotation()?;
let directives = self.parse_constant_directives()?;
Ok(FieldDefinition {
name,
arguments,
type_,
directives,
})
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
fn parse_argument_defs(&mut self) -> ParseResult<Option<List<InputValueDefinition>>> {
self.parse_optional_delimited_nonempty_list(
TokenKind::OpenParen,
TokenKind::CloseParen,
Self::parse_input_value_def,
)
}
/**
* InputValueDefinition :
* - Description? Name : Type DefaultValue? Directives?
*/
fn parse_input_value_def(&mut self) -> ParseResult<InputValueDefinition> {
self.parse_optional_description();
let name = self.parse_identifier()?;
self.parse_kind(TokenKind::Colon)?;
let type_ = self.parse_type_annotation()?;
let default_value = if self.parse_optional_kind(TokenKind::Equals).is_some() {
Some(self.parse_constant_value()?)
} else {
None
};
let directives = self.parse_constant_directives()?;
Ok(InputValueDefinition {
name,
type_,
default_value,
directives,
})
}
/**
* ImplementsInterfaces :
* - implements `&`? NamedType
* - ImplementsInterfaces & NamedType
*/
fn parse_implements_interfaces(&mut self) -> ParseResult<Vec<Identifier>> {
let mut interfaces = Vec::new();
if self.peek_keyword("implements") {
self.parse_token();
self.parse_optional_kind(TokenKind::Ampersand);
interfaces.push(self.parse_identifier()?);
while self.parse_optional_kind(TokenKind::Ampersand).is_some() {
interfaces.push(self.parse_identifier()?);
}
}
Ok(interfaces)
}
/// FragmentDefinition : fragment FragmentName TypeCondition Directives? SelectionSet
fn parse_fragment_definition(&mut self) -> ParseResult<FragmentDefinition> {
let start = self.index();
let fragment = self.parse_keyword("fragment")?;
let name = self.parse_identifier()?;
let variable_definitions = if self.features.enable_variable_definitions {
self.parse_optional_delimited_nonempty_list(
TokenKind::OpenParen,
TokenKind::CloseParen,
Self::parse_variable_definition,
)?
} else {
None
};
let type_condition = self.parse_type_condition()?;
let directives = self.parse_directives()?;
let selections = self.parse_selections()?;
let end = self.end_index;
let span = Span::new(start, end);
Ok(FragmentDefinition {
location: Location::new(self.source_location, span),
fragment,
name,
variable_definitions,
type_condition,
directives,
selections,
})
}
/// OperationDefinition :
/// OperationType Name? VariableDefinitions? Directives? SelectionSet
/// SelectionSet
fn parse_operation_definition(&mut self) -> ParseResult<OperationDefinition> {
let start = self.index();
// Special case: anonymous query
if self.peek_token_kind() == TokenKind::OpenBrace {
let selections = self.parse_selections()?;
let span = Span::new(start, self.end_index);
return Ok(OperationDefinition {
location: Location::new(self.source_location, span),
operation: None,
name: None,
variable_definitions: None,
directives: Vec::new(),
selections,
});
}
// Otherwise requires operation type and name
let maybe_operation_token = self.peek();
let operation = match (
maybe_operation_token.kind,
self.source(&maybe_operation_token),
) {
(TokenKind::Identifier, "mutation") => (self.parse_token(), OperationKind::Mutation),
(TokenKind::Identifier, "query") => (self.parse_token(), OperationKind::Query),
(TokenKind::Identifier, "subscription") => {
(self.parse_token(), OperationKind::Subscription)
}
_ => {
let error = Diagnostic::error(
SyntaxError::ExpectedOperationKind,
Location::new(self.source_location, maybe_operation_token.span),
);
self.record_error(error);
return Err(());
}
};
let name = if self.peek_token_kind() == TokenKind::Identifier {
Some(self.parse_identifier()?)
} else {
None
};
let variable_definitions = self.parse_optional_delimited_nonempty_list(
TokenKind::OpenParen,
TokenKind::CloseParen,
Self::parse_variable_definition,
)?;
let directives = self.parse_directives()?;
let selections = self.parse_selections()?;
let span = Span::new(start, self.end_index);
Ok(OperationDefinition {
location: Location::new(self.source_location, span),
operation: Some(operation),
name,
variable_definitions,
directives,
selections,
})
}
/// VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
fn parse_variable_definition(&mut self) -> ParseResult<VariableDefinition> {
let start = self.index();
let name = self.parse_variable_identifier()?;
let colon = self.parse_kind(TokenKind::Colon)?;
let type_ = self.parse_type_annotation()?;
let default_value = if self.peek_token_kind() == TokenKind::Equals {
Some(self.parse_default_value()?)
} else {
None
};
let directives = self.parse_directives()?;
let span = Span::new(start, self.end_index);
Ok(VariableDefinition {
span,
name,
colon,
type_,
default_value,
directives,
})
}
/// DefaultValue : = Value[Const]
fn parse_default_value(&mut self) -> ParseResult<DefaultValue> {
let start = self.index();
let equals = self.parse_kind(TokenKind::Equals)?;
let value = self.parse_constant_value()?;
let span = Span::new(start, self.end_index);
Ok(DefaultValue {
span,
equals,
value,
})
}
/// Type :
/// NamedType
/// ListType
/// NonNullType
fn parse_type_annotation(&mut self) -> ParseResult<TypeAnnotation> {
let start = self.index();
let token = self.peek();
let type_annotation = match token.kind {
TokenKind::Identifier => TypeAnnotation::Named(self.parse_identifier()?),
TokenKind::OpenBracket => {
let open = self.parse_kind(TokenKind::OpenBracket)?;
let type_ = self.parse_type_annotation()?;
let close = self.parse_kind(TokenKind::CloseBracket)?;
TypeAnnotation::List(Box::new(ListTypeAnnotation {
span: Span::new(start, self.end_index),
open,
type_,
close,
}))
}
_ => {
let error = Diagnostic::error(
SyntaxError::ExpectedTypeAnnotation,
Location::new(self.source_location, token.span),
);
self.record_error(error);
return Err(());
}
};
if self.peek_token_kind() == TokenKind::Exclamation {
let exclamation = self.parse_kind(TokenKind::Exclamation)?;
Ok(TypeAnnotation::NonNull(Box::new(NonNullTypeAnnotation {
span: Span::new(start, self.end_index),
type_: type_annotation,
exclamation,
})))
} else {
Ok(type_annotation)
}
}
/// Directives[Const] : Directive[?Const]+
fn parse_directives(&mut self) -> ParseResult<Vec<Directive>> {
self.parse_list(|s| s.peek_kind(TokenKind::At), |s| s.parse_directive_impl())
}
fn parse_constant_directives(&mut self) -> ParseResult<Vec<ConstantDirective>> {
if self.peek_token_kind() == TokenKind::At {
self.parse_list(
|s| s.peek_kind(TokenKind::At),
|s| s.parse_constant_directive(),
)
} else {
Ok(vec![])
}
}
/// Directive[Const] : @ Name Arguments[?Const]?<|fim▁hole|> fn parse_directive_impl(&mut self) -> ParseResult<Directive> {
let start = self.index();
let at = self.parse_kind(TokenKind::At)?;
let name = self.parse_identifier_with_error_recovery();
let arguments = self.parse_optional_arguments()?;
let span = Span::new(start, self.end_index);
Ok(Directive {
span,
at,
name,
arguments,
})
}
fn parse_constant_directive(&mut self) -> ParseResult<ConstantDirective> {
let start = self.index();
let at = self.parse_kind(TokenKind::At)?;
let name = self.parse_identifier()?;
let arguments = self.parse_optional_constant_arguments()?;
let span = Span::new(start, self.end_index);
Ok(ConstantDirective {
span,
at,
name,
arguments,
})
}
/// TypeCondition : on NamedType
/// NamedType : Name
fn parse_type_condition(&mut self) -> ParseResult<TypeCondition> {
let start = self.index();
let on = self.parse_keyword("on")?;
let type_ = self.parse_identifier()?;
Ok(TypeCondition {
span: Span::new(start, self.end_index),
on,
type_,
})
}
/// SelectionSet : { Selection+ }
fn parse_selections(&mut self) -> ParseResult<List<Selection>> {
self.parse_delimited_nonempty_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
Self::parse_selection,
)
}
/// Selection :
/// Field
/// FragmentSpread
/// InlineFragment
fn parse_selection(&mut self) -> ParseResult<Selection> {
let token = self.peek();
match token.kind {
TokenKind::Spread => self.parse_spread(),
TokenKind::Identifier => self.parse_field(),
// hint for invalid spreads
TokenKind::Period | TokenKind::PeriodPeriod => {
let error = Diagnostic::error(
SyntaxError::ExpectedSpread,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
_ => {
let error = Diagnostic::error(
SyntaxError::ExpectedSelection,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/// Field : Alias? Name Arguments? Directives? SelectionSet?
fn parse_field(&mut self) -> ParseResult<Selection> {
let start = self.index();
let name = self.parse_identifier()?;
let (name, alias) = if self.peek_token_kind() == TokenKind::Colon {
let colon = self.parse_kind(TokenKind::Colon)?;
let alias = name;
let name = self.parse_identifier()?;
(
name,
Some(Alias {
span: Span::new(start, self.end_index),
alias,
colon,
}),
)
} else {
(name, None)
};
let arguments = self.parse_optional_arguments()?;
let directives = self.parse_directives()?;
if self.peek_token_kind() == TokenKind::OpenBrace {
let selections = self.parse_selections()?;
Ok(Selection::LinkedField(LinkedField {
span: Span::new(start, self.end_index),
alias,
name,
arguments,
directives,
selections,
}))
} else {
Ok(Selection::ScalarField(ScalarField {
span: Span::new(start, self.end_index),
alias,
name,
arguments,
directives,
}))
}
}
/// FragmentSpread : ... FragmentName Directives?
/// InlineFragment : ... TypeCondition? Directives? SelectionSet
fn parse_spread(&mut self) -> ParseResult<Selection> {
let start = self.index();
let spread = self.parse_kind(TokenKind::Spread)?;
let is_on_keyword = self.peek_keyword("on");
if !is_on_keyword && self.peek_token_kind() == TokenKind::Identifier {
// fragment spread
let name = self.parse_identifier()?;
let directives = self.parse_directives()?;
Ok(Selection::FragmentSpread(FragmentSpread {
span: Span::new(start, self.end_index),
spread,
name,
directives,
}))
} else {
// inline fragment with or without a type condition
let type_condition = if is_on_keyword {
Some(self.parse_type_condition()?)
} else {
None
};
let directives = self.parse_directives()?;
let selections = self.parse_selections()?;
Ok(Selection::InlineFragment(InlineFragment {
span: Span::new(start, self.end_index),
spread,
type_condition,
directives,
selections,
}))
}
}
/// Arguments?
/// Arguments[Const] : ( Argument[?Const]+ )
fn parse_optional_arguments(&mut self) -> ParseResult<Option<List<Argument>>> {
if self.peek_token_kind() != TokenKind::OpenParen {
return Ok(None);
}
let start = self.parse_token();
let mut items: Vec<Argument> = vec![];
loop {
let peek_kind = self.peek_token_kind();
if peek_kind == TokenKind::CloseParen {
break;
} else if peek_kind == TokenKind::OpenBrace || peek_kind == TokenKind::CloseBrace {
self.record_error(Diagnostic::error(
SyntaxError::Expected(TokenKind::CloseParen),
Location::new(self.source_location, self.peek().span),
));
let span = Span::new(start.span.start, self.end_index);
if items.is_empty() {
self.record_error(Diagnostic::error(
SyntaxError::ExpectedArgument,
Location::new(self.source_location, span),
))
}
return Ok(Some(List {
span,
start,
items,
end: self.empty_token(),
}));
}
// MaybeArgument Name ?: ?Value[?Const]
let start = self.index();
let name = if peek_kind == TokenKind::Identifier {
self.parse_identifier()?
} else {
(|| {
if peek_kind == TokenKind::Colon && !items.is_empty() {
/*
(
arg:
arg2: $var
# ^ We are at the second colon, and need to recover the identifier
)
*/
let last_arg = items.last_mut().unwrap();
if let Value::Constant(ConstantValue::Enum(node)) = &last_arg.value {
self.record_error(Diagnostic::error(
SyntaxError::ExpectedValue,
Location::new(
self.source_location,
Span::new(last_arg.colon.span.end, last_arg.colon.span.end),
),
));
let name = Identifier {
span: node.token.span,
token: node.token.clone(),
value: node.value,
};
last_arg.span.end = last_arg.colon.span.end;
last_arg.value = Value::Constant(ConstantValue::Null(Token {
span: Span::new(last_arg.span.end, last_arg.span.end),
kind: TokenKind::Empty,
}));
return name;
}
}
/*
($var)
(:$var)
*/
self.record_error(Diagnostic::error(
SyntaxError::Expected(TokenKind::Identifier),
Location::new(
self.source_location,
Span::new(start, self.peek().span.start),
),
));
let empty_token = self.empty_token();
Identifier {
span: empty_token.span,
token: empty_token,
value: "".intern(),
}
})()
};
let colon = self.parse_optional_kind(TokenKind::Colon);
if let Some(colon) = colon {
if self.peek_kind(TokenKind::CloseParen) {
self.record_error(Diagnostic::error(
SyntaxError::ExpectedValue,
Location::new(
self.source_location,
Span::new(name.span.end, self.end_index),
),
));
let span = Span::new(start, self.end_index);
let value = Value::Constant(ConstantValue::Null(self.empty_token()));
items.push(Argument {
span,
name,
colon,
value,
});
} else {
let value = self.parse_value()?;
let span = Span::new(start, self.end_index);
items.push(Argument {
span,
name,
colon,
value,
});
}
} else {
self.record_error(Diagnostic::error(
SyntaxError::Expected(TokenKind::Colon),
Location::new(self.source_location, Span::new(name.span.end, self.index())),
));
// Continue parsing value if the next token looks like a value (except for Enum)
// break early if the next token is not a valid token for the next argument
let mut should_break = false;
let value = match self.peek_token_kind() {
TokenKind::Dollar
| TokenKind::OpenBrace
| TokenKind::OpenBracket
| TokenKind::StringLiteral
| TokenKind::IntegerLiteral
| TokenKind::FloatLiteral => self.parse_value()?,
TokenKind::Identifier => {
let source = self.source(self.peek());
if source == "true" || source == "false" || source == "null" {
self.parse_value()?
} else {
Value::Constant(ConstantValue::Null(self.empty_token()))
}
}
TokenKind::CloseParen | TokenKind::Colon => {
Value::Constant(ConstantValue::Null(self.empty_token()))
}
_ => {
should_break = true;
Value::Constant(ConstantValue::Null(self.empty_token()))
}
};
let span = Span::new(start, self.end_index);
items.push(Argument {
span,
name,
colon: self.empty_token(),
value,
});
if should_break {
break;
}
}
}
let end = self.parse_token();
let span = Span::new(start.span.start, end.span.end);
if items.is_empty() {
self.record_error(Diagnostic::error(
SyntaxError::ExpectedArgument,
Location::new(self.source_location, span),
))
}
Ok(Some(List {
span,
start,
items,
end,
}))
}
fn parse_optional_constant_arguments(&mut self) -> ParseResult<Option<List<ConstantArgument>>> {
self.parse_optional_delimited_nonempty_list(
TokenKind::OpenParen,
TokenKind::CloseParen,
Self::parse_constant_argument,
)
}
/// Argument[Const] : Name : Value[?Const]
fn parse_argument(&mut self) -> ParseResult<Argument> {
let start = self.index();
let name = self.parse_identifier()?;
let colon = self.parse_kind(TokenKind::Colon)?;
let value = self.parse_value()?;
let span = Span::new(start, self.end_index);
Ok(Argument {
span,
name,
colon,
value,
})
}
/// Argument[Const=true] : Name : Value[Const=true]
fn parse_constant_argument(&mut self) -> ParseResult<ConstantArgument> {
let start = self.index();
let name = self.parse_identifier()?;
let colon = self.parse_kind(TokenKind::Colon)?;
let value = self.parse_constant_value()?;
let span = Span::new(start, self.end_index);
Ok(ConstantArgument {
span,
name,
colon,
value,
})
}
/// Value[?Const] :
/// [~Const] Variable
/// ListValue[?Const]
/// ObjectValue[?Const]
// (delegated):
/// IntValue
/// FloatValue
/// StringValue
/// BooleanValue
/// NullValue
/// EnumValue
fn parse_value(&mut self) -> ParseResult<Value> {
let token = self.peek();
match token.kind {
TokenKind::OpenBracket => {
let list = self.parse_delimited_list(
TokenKind::OpenBracket,
TokenKind::CloseBracket,
|s| s.parse_value(),
)?;
// Promote a Value::List() with all constant items to Value::Constant()
if list.items.iter().all(|x| x.is_constant()) {
let mut constants = Vec::with_capacity(list.items.len());
for item in list.items {
match item {
Value::Constant(c) => {
constants.push(c);
}
_ => unreachable!("Already checked all items are constant"),
}
}
Ok(Value::Constant(ConstantValue::List(List {
span: list.span,
start: list.start,
items: constants,
end: list.end,
})))
} else {
Ok(Value::List(list))
}
}
TokenKind::OpenBrace => {
let list =
self.parse_delimited_list(TokenKind::OpenBrace, TokenKind::CloseBrace, |s| {
s.parse_argument()
})?;
// Promote a Value::Object() with all constant values to Value::Constant()
if list.items.iter().all(|x| x.value.is_constant()) {
let mut arguments = Vec::with_capacity(list.items.len());
for argument in list.items {
let value = match argument.value {
Value::Constant(c) => c,
_ => unreachable!("Already checked all items are constant"),
};
arguments.push(ConstantArgument {
span: argument.span,
name: argument.name,
colon: argument.colon,
value,
});
}
Ok(Value::Constant(ConstantValue::Object(List {
span: list.span,
start: list.start,
items: arguments,
end: list.end,
})))
} else {
Ok(Value::Object(list))
}
}
TokenKind::Dollar => Ok(Value::Variable(self.parse_variable_identifier()?)),
_ => Ok(Value::Constant(self.parse_literal_value()?)),
}
}
// Constant Values
/// Value[Const=true] :
/// IntValue
/// FloatValue
/// StringValue
/// BooleanValue
/// NullValue
/// EnumValue
/// ListValue[Const=true]
/// ObjectValue[Const=true]
fn parse_constant_value(&mut self) -> ParseResult<ConstantValue> {
match self.peek_token_kind() {
TokenKind::OpenBracket => Ok(ConstantValue::List(self.parse_delimited_list(
TokenKind::OpenBracket,
TokenKind::CloseBracket,
|s| s.parse_constant_value(),
)?)),
TokenKind::OpenBrace => Ok(ConstantValue::Object(self.parse_delimited_list(
TokenKind::OpenBrace,
TokenKind::CloseBrace,
|s| s.parse_constant_argument(),
)?)),
_ => self.parse_literal_value(),
}
}
/// IntValue
/// FloatValue
/// StringValue
/// BooleanValue
/// NullValue
/// EnumValue
fn parse_literal_value(&mut self) -> ParseResult<ConstantValue> {
let token = self.parse_token();
let source = self.source(&token);
match &token.kind {
TokenKind::StringLiteral => {
let value = source[1..source.len() - 1].to_string();
Ok(ConstantValue::String(StringNode {
token,
value: value.intern(),
}))
}
TokenKind::IntegerLiteral => {
let value = source.parse::<i64>();
match value {
Ok(value) => Ok(ConstantValue::Int(IntNode { token, value })),
Err(_) => {
let error = Diagnostic::error(
SyntaxError::InvalidInteger,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
TokenKind::FloatLiteral => {
let value = source.parse::<f64>();
match value {
Ok(value) => Ok(ConstantValue::Float(FloatNode {
token,
value: FloatValue::new(value),
source_value: source.intern(),
})),
Err(_) => {
let error = Diagnostic::error(
SyntaxError::InvalidFloat,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
TokenKind::Identifier => Ok(match source {
"true" => ConstantValue::Boolean(BooleanNode { token, value: true }),
"false" => ConstantValue::Boolean(BooleanNode {
token,
value: false,
}),
"null" => ConstantValue::Null(token),
_ => ConstantValue::Enum(EnumNode {
token,
value: source.intern(),
}),
}),
TokenKind::ErrorFloatLiteralMissingZero => {
let error = Diagnostic::error(
SyntaxError::InvalidFloatLiteralMissingZero,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
TokenKind::ErrorNumberLiteralLeadingZero
| TokenKind::ErrorNumberLiteralTrailingInvalid => {
let error = Diagnostic::error(
SyntaxError::InvalidNumberLiteral,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
TokenKind::ErrorUnsupportedStringCharacter => {
let error = Diagnostic::error(
SyntaxError::UnsupportedStringCharacter,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
TokenKind::ErrorUnterminatedString => {
let error = Diagnostic::error(
SyntaxError::UnterminatedString,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
TokenKind::ErrorUnterminatedBlockString => {
let error = Diagnostic::error(
SyntaxError::UnterminatedBlockString,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
_ => {
let error = Diagnostic::error(
SyntaxError::ExpectedConstantValue,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
}
/// Variable : $ Name
fn parse_variable_identifier(&mut self) -> ParseResult<VariableIdentifier> {
let start = self.index();
let dollar_token = self.parse_token();
if dollar_token.kind != TokenKind::Dollar {
self.record_error(Diagnostic::error(
SyntaxError::ExpectedVariable,
Location::new(self.source_location, dollar_token.span),
));
return Err(());
}
let token = self.parse_token();
if token.kind == TokenKind::Identifier {
let name = self.source(&token).intern();
Ok(VariableIdentifier {
span: Span::new(start, token.span.end),
token,
name,
})
} else {
let error = Diagnostic::error(
SyntaxError::ExpectedVariableIdentifier,
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
/// Name :: /[_A-Za-z][_0-9A-Za-z]*/
fn parse_identifier(&mut self) -> ParseResult<Identifier> {
let token = self.parse_token();
let source = self.source(&token);
let span = token.span;
match token.kind {
TokenKind::Identifier => Ok(Identifier {
span,
token,
value: source.intern(),
}),
_ => {
let error = Diagnostic::error(
SyntaxError::Expected(TokenKind::Identifier),
Location::new(self.source_location, span),
);
self.record_error(error);
Err(())
}
}
}
fn parse_identifier_with_error_recovery(&mut self) -> Identifier {
match self.peek_token_kind() {
TokenKind::Identifier => {
let token = self.parse_token();
let source = self.source(&token);
let span = token.span;
Identifier {
span,
token,
value: source.intern(),
}
}
_ => {
let token = self.empty_token();
let error = Diagnostic::error(
SyntaxError::Expected(TokenKind::Identifier),
Location::new(self.source_location, token.span),
);
self.record_error(error);
Identifier {
span: token.span,
token,
value: "".intern(),
}
}
}
}
// Helpers
/// <item>*
fn parse_list<T, F1, F2>(&mut self, peek: F1, parse: F2) -> ParseResult<Vec<T>>
where
F1: Fn(&mut Self) -> bool,
F2: Fn(&mut Self) -> ParseResult<T>,
{
let mut items = vec![];
while peek(self) {
items.push(parse(self)?);
}
Ok(items)
}
/// Parse delimited items into a `List`
/// <start> <item>* <end>
fn parse_delimited_list<T, F>(
&mut self,
start_kind: TokenKind,
end_kind: TokenKind,
parse: F,
) -> ParseResult<List<T>>
where
F: Fn(&mut Self) -> ParseResult<T>,
{
let start = self.parse_kind(start_kind)?;
let mut items = vec![];
while !self.peek_kind(end_kind) {
items.push(parse(self)?);
}
let end = self.parse_kind(end_kind)?;
let span = Span::new(start.span.start, end.span.end);
Ok(List {
span,
start,
items,
end,
})
}
/// Parse delimited items into a `List`
/// <start> <item>+ <end>
fn parse_delimited_nonempty_list<T, F>(
&mut self,
start_kind: TokenKind,
end_kind: TokenKind,
parse: F,
) -> ParseResult<List<T>>
where
F: Fn(&mut Self) -> ParseResult<T>,
{
if !self.peek_kind(start_kind) {
let error = Diagnostic::error(
SyntaxError::Expected(start_kind),
Location::new(
self.source_location,
Span::new(self.end_index, self.index()),
),
);
self.record_error(error);
let token = self.empty_token();
return Ok(List {
span: token.span,
start: token.clone(),
items: vec![],
end: token,
});
}
let start = self.parse_token();
let mut items = vec![];
while !self.peek_kind(end_kind) {
items.push(parse(self)?);
}
let end = self.parse_kind(end_kind)?;
let span = Span::new(start.span.start, end.span.end);
if items.is_empty() {
self.record_error(Diagnostic::error(
SyntaxError::ExpectedNonEmptyList,
Location::new(self.source_location, span),
));
}
Ok(List {
span,
start,
items,
end,
})
}
/// (<start> <item>+ <end>)?
fn parse_optional_delimited_nonempty_list<T, F>(
&mut self,
start_kind: TokenKind,
end_kind: TokenKind,
parse: F,
) -> ParseResult<Option<List<T>>>
where
F: Fn(&mut Self) -> ParseResult<T>,
{
if self.peek_token_kind() == start_kind {
Ok(Some(self.parse_delimited_nonempty_list(
start_kind, end_kind, parse,
)?))
} else {
Ok(None)
}
}
/// A &str for the source of the inner span of the given token.
fn source(&self, token: &Token) -> &str {
let (start, end) = token.span.as_usize();
&self.source[start..end]
}
/// Peek at the next token
fn peek(&self) -> &Token {
&self.current
}
/// Return true if the next token has the expected kind
fn peek_kind(&self, expected: TokenKind) -> bool {
self.peek_token_kind() == expected
}
/// Peek at the kind of the next token
fn peek_token_kind(&self) -> TokenKind {
self.current.kind
}
/// Parse the next token, succeeding if it has the expected kind and failing
/// otherwise.
fn parse_kind(&mut self, expected: TokenKind) -> ParseResult<Token> {
let start = self.index();
let token = self.parse_token();
if token.kind == expected {
Ok(token)
} else {
let error = Diagnostic::error(
SyntaxError::Expected(expected),
Location::new(self.source_location, Span::new(start, self.end_index)),
);
self.record_error(error);
Err(())
}
}
/// Parse the next token if it has the expected kind.
fn parse_optional_kind(&mut self, expected: TokenKind) -> Option<Token> {
if self.peek_kind(expected) {
Some(self.parse_token())
} else {
None
}
}
/// Return true if the current token is an Identifier matching the given keyword.
fn peek_keyword(&self, expected: &'static str) -> bool {
self.peek_kind(TokenKind::Identifier) && self.source(self.peek()) == expected
}
/// Parse the next token, succeeding if it is an Identifier that matches the
/// given keyword
fn parse_keyword(&mut self, expected: &'static str) -> ParseResult<Token> {
let token = self.parse_kind(TokenKind::Identifier)?;
if self.source(&token) == expected {
Ok(token)
} else {
let error = Diagnostic::error(
SyntaxError::ExpectedKeyword(expected),
Location::new(self.source_location, token.span),
);
self.record_error(error);
Err(())
}
}
/// Get the byte offset of the *start* of the current token
fn index(&self) -> u32 {
self.current.span.start
}
/// Get the next token (and advance)
fn parse_token(&mut self) -> Token {
// Skip over (and record) any invalid tokens until either a valid token or an EOF is encountered
loop {
let kind = self.lexer.next().unwrap_or(TokenKind::EndOfFile);
match kind {
TokenKind::Error => {
if let Some(error_token_kind) = self.lexer.extras.error_token {
// Reset the error token
self.lexer.extras.error_token = None;
// If error_token is set, return that error token
// instead of a generic error.
self.end_index = self.current.span.end;
return std::mem::replace(
&mut self.current,
Token {
kind: error_token_kind,
span: self.lexer.span().into(),
},
);
} else {
// Record and skip over unknown character errors
let error = Diagnostic::error(
SyntaxError::UnsupportedCharacter,
Location::new(self.source_location, self.lexer.span().into()),
);
self.record_error(error);
}
}
_ => {
self.end_index = self.current.span.end;
return std::mem::replace(
&mut self.current,
Token {
kind,
span: self.lexer.span().into(),
},
);
}
}
}
}
fn record_error(&mut self, error: Diagnostic) {
// NOTE: Useful for debugging parse errors:
// panic!("{:?}", error);
self.errors.push(error);
}
/// Returns an empty token with a span at the end of last token
fn empty_token(&self) -> Token {
let index = self.end_index;
Token {
span: Span::new(index, index),
kind: TokenKind::Empty,
}
}
}<|fim▁end|> | |
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-18 12:59
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
import wagtail.search.index
class Migration(migrations.Migration):
initial = True
dependencies = [
('taggit', '0002_auto_20150616_2121'),
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('date_of_birth', models.DateField(null=True)),
],<|fim▁hole|> name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('publication_date', models.DateField()),
('number_of_pages', models.IntegerField()),
],
bases=(models.Model, wagtail.search.index.Indexed),
),
migrations.CreateModel(
name='Character',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='Novel',
fields=[
('book_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='searchtests.Book')),
('setting', models.CharField(max_length=255)),
('protagonist', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='searchtests.Character')),
],
bases=('searchtests.book',),
),
migrations.CreateModel(
name='ProgrammingGuide',
fields=[
('book_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='searchtests.Book')),
('programming_language', models.CharField(choices=[('py', 'Python'), ('js', 'JavaScript'), ('rs', 'Rust')], max_length=255)),
],
bases=('searchtests.book',),
),
migrations.AddField(
model_name='book',
name='authors',
field=models.ManyToManyField(related_name='books', to='searchtests.Author'),
),
migrations.AddField(
model_name='book',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
migrations.AddField(
model_name='character',
name='novel',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='characters', to='searchtests.Novel'),
),
]<|fim▁end|> | bases=(models.Model, wagtail.search.index.Indexed),
),
migrations.CreateModel( |
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
)
func SumArray(arr []uint64) uint64 {
var sum uint64
for _, i := range arr {
sum += i
}
return sum
}
func main() {
var count uint64
fmt.Scan(&count)
array := make([]uint64, count)<|fim▁hole|> for i := range array {
fmt.Scan(&array[i])
}
fmt.Println(SumArray(array))
}<|fim▁end|> | |
<|file_name|>test_smtp.py<|end_file_name|><|fim▁begin|>import sys
import smtplib
<|fim▁hole|>def output((code, msg)):
sys.stdout.write('%s %s\n' % (code, msg))
sys.stdout.flush()
smtp = smtplib.SMTP('localhost', 2500)
output(smtp.ehlo('moon.localdomain'))
print smtp.esmtp_features
output(smtp.mail('Damien Churchill <[email protected]>'))
output(smtp.rcpt('Damien Churchill <[email protected]>'))
output(smtp.data('Subject: Testing\n\nTest'))
output(smtp.quit())<|fim▁end|> | |
<|file_name|>main.js<|end_file_name|><|fim▁begin|>'use strict';
describe('Controller: MainCtrl', function() {
// load the controller's module
beforeEach(module('actionatadistanceApp'));
var MainCtrl,<|fim▁hole|> scope = {};
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function() {
expect(scope.awesomeThings.length).toBe(3);
});
});<|fim▁end|> | scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller) { |
<|file_name|>udup_ablation.py<|end_file_name|><|fim▁begin|>from collections import defaultdict, Counter
from pathlib import Path
import argparse
import sys, copy
import networkx as nx
import numpy as np
from lib.conll import CoNLLReader, DependencyTree
from pandas import pandas as pd
OPEN="ADJ ADV INTJ NOUN PROPN VERB".split()
CLOSED="ADP AUX CONJ DET NUM PART PRON SCONJ".split()
OTHER="PUNCT SYM X".split()
CONTENT="ADJ NOUN PROPN VERB CONTENT".split(" ")
FUNCTION="ADP AUX CONJ DET NUM PART PRON SCONJ PUNCT SYM X ADV FUNCTION".split(" ")
RIGHTATTACHING = []
LEFTATTACHING = []
scorerdict = defaultdict(list)
def map_to_two_tags(s,functionlist):
for n in list(s.nodes()):
if s.node[n]['form'].lower() in functionlist:
s.nodes[n]['cpostag'] = 'FUNCTION'
else:
s.nodes[n]['cpostag'] = 'CONTENT'
return s
def get_head_direction(sentences):
D = Counter()
for s in sentences:
for h,d in s.edges():
if h != 0 and h > d:
D[s.nodes[d]['cpostag']+"_right"]+=1
else:
D[s.nodes[d]['cpostag']+"_left"]+=1
for k in sorted(D.keys()):
print(k,D[k])
def fill_out_left_and_right_attach(bigramcounter):
LEFTATTACHING.append("CONJ")
LEFTATTACHING.append("PUNCT")
LEFTATTACHING.append("PROPN")
RIGHTATTACHING.append("AUX")
RIGHTATTACHING.append("DET")
RIGHTATTACHING.append("SCONJ")
if bigramcounter[("ADP","DET")] + bigramcounter[("ADP","NOUN")] + bigramcounter[("ADP","PROPN")] + bigramcounter[("ADP","PRON")] > bigramcounter[("DET","ADP")] + bigramcounter[("NOUN","ADP")] + bigramcounter[("PROPN","ADP")] + bigramcounter[("PRON","ADP")]:
RIGHTATTACHING.append("ADP")
else:
LEFTATTACHING.append("ADP")
def get_scores(predset,goldset):
tp = len(predset.intersection(goldset))
fp = len(predset.difference(goldset))
fn = len(goldset.difference(predset))
try:
precision = tp / (fp + tp)
except:
precision = 0
try:
recall = tp / (fn + tp)
except:
recall = 0
return (precision,recall)
def count_pos_bigrams(treebank):
C = Counter()
W = Counter()
for s in treebank:
for n,n_next in zip(list(s.nodes()[1:]),list(s.nodes()[2:])):
pos_n = s.node[n]['cpostag']
pos_n_next = s.node[n_next]['cpostag']
C[(pos_n,pos_n_next)]+=1
for n in s.nodes()[1:]:
word_n = s.node[n]['form'].lower()
W[word_n]+=1
return C,W
def add_high_confidence_edges(s,bigramcount,backoff):
pos_index_dict = defaultdict(list)
T = set()
D = set()
goldedgeset=set(s.edges())
global scorerdict
verbroot = None
adjroot = None
possibleheads = [x for x in s.nodes() if s.node[x]['cpostag'] in OPEN]
if len(possibleheads) == 1:
T.add((0,possibleheads[0]))
for d in s.nodes():
if d != 0 and d!= possibleheads[0]:
T.add((possibleheads[0],d))
scorerdict["__shortsentence"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
else:
for n in s.nodes():
pos_index_dict[s.node[n]['cpostag']].append(n)
for n in pos_index_dict["DET"]:
#if bigramcount[("DET","NOUN")] > bigramcount[("NOUN","DET")]:
# noundist=[abs(n-x) for x in pos_index_dict["NOUN"] if x > n ]
#else:
# noundist=[abs(n-x) for x in pos_index_dict["NOUN"] if x < n ]
noundist=[abs(n-x) for x in pos_index_dict["NOUN"]]
if noundist:
closestnoun=pos_index_dict["NOUN"][np.argmin(noundist)]
T.add((closestnoun,n))
localgoldedgeset = set([(h,d) for h,d in goldedgeset if d in pos_index_dict["DET"]])
scorerdict["DET"].append(get_scores(T,localgoldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["NUM"]:
#if bigramcount[("DET","NOUN")] > bigramcount[("NOUN","DET")]:
# noundist=[abs(n-x) for x in pos_index_dict["NOUN"] if x > n ]
#else:
# noundist=[abs(n-x) for x in pos_index_dict["NOUN"] if x < n ]
noundist=[abs(n-x) for x in pos_index_dict["NOUN"]]
if noundist:
closestnoun=pos_index_dict["NOUN"][np.argmin(noundist)]
T.add((closestnoun,n))
localgoldedgeset = set([(h,d) for h,d in goldedgeset if d in pos_index_dict["DET"]])
scorerdict["NUM"].append(get_scores(T,localgoldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["ADP"]:
# if bigramcount[("ADP","NOUN")] > bigramcount[("NOUN","ADP")]:
# noundist=[abs(n-x) for x in pos_index_dict["NOUN"] if x > n ]
# else:
# noundist=[abs(n-x) for x in pos_index_dict["NOUN"] if x < n ]
noundist=[abs(n-x) for x in pos_index_dict["NOUN"] ]
if noundist:
closestnoun=pos_index_dict["NOUN"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["ADP"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["ADJ"]:
# if bigramcount[("adj","noun")] > bigramcount[("noun","adj")]:
# noundist=[abs(n-x) for x in pos_index_dict["noun"] if x > n ]
# else:
# noundist=[abs(n-x) for x in pos_index_dict["noun"] if x < n ]
noundist=[abs(n-x) for x in pos_index_dict["NOUN"] ]
if noundist:
closestnoun=pos_index_dict["NOUN"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["ADJ_nounhead"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["AUX"]:
# if bigramcount[("AUX","VERB")] > bigramcount[("VERB","AUX")]:
# noundist=[abs(n-x) for x in pos_index_dict["VERB"] if x > n ]
# else:
# noundist=[abs(n-x) for x in pos_index_dict["VERB"] if x < n ]
noundist=[abs(n-x) for x in pos_index_dict["VERB"] ]
if noundist:
closestnoun=pos_index_dict["VERB"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["AUX"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["NOUN"]:
# if bigramcount[("AUX","VERB")] > bigramcount[("VERB","AUX")]:
# noundist=[abs(n-x) for x in pos_index_dict["VERB"] if x > n ]
# else:
# noundist=[abs(n-x) for x in pos_index_dict["VERB"] if x < n ]
noundist=[abs(n-x) for x in pos_index_dict["VERB"] ]
if noundist:
closestnoun=pos_index_dict["VERB"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["NOUN"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["PRON"]:
noundist=[abs(n-x) for x in pos_index_dict["VERB"]]
if noundist:
closestnoun=pos_index_dict["VERB"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["PRON"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["ADV"]:
noundist=[abs(n-x) for x in pos_index_dict["VERB"]+pos_index_dict["ADJ"]]
if noundist:
closestnoun=(pos_index_dict["VERB"]+pos_index_dict["ADJ"])[np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["ADV"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
if pos_index_dict["VERB"]:
verbroot = min(pos_index_dict["VERB"])
T.add((0,verbroot))
scorerdict["VERB_root"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["VERB"]:
noundist=[abs(n-x) for x in pos_index_dict["VERB"] if x != n and n != verbroot]
if noundist:
closestnoun=pos_index_dict["VERB"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["VERB_head"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
for n in pos_index_dict["SCONJ"]:
noundist=[abs(n-x) for x in pos_index_dict["VERB"]]
if noundist:
closestnoun=pos_index_dict["VERB"][np.argmin(noundist)]
T.add((closestnoun,n))
scorerdict["SCONJ"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
elif pos_index_dict["ADJ"] or pos_index_dict["NOUN"]: #or pos_index_dict["PROPN"]:
adjroot = min(pos_index_dict["ADJ"]+pos_index_dict["NOUN"])#+pos_index_dict["PROPN"])
T.add((0,adjroot))
scorerdict["CONTENT_root"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
if pos_index_dict["PROPN"]:
li = sorted(pos_index_dict["PROPN"])
operation = []
for idx,v in enumerate(li):
if idx == 0:
operation.append("head")
elif v -1 == li[idx-1]:
operation.append("dep")
else:
operation.append("head")
for v, o in zip(li,operation):
if o == 'head':
head = v
else:
T.add((head,v))
scorerdict["PROPN_chain"].append(get_scores(T,goldedgeset))
D.update(T)
T = set()
if s.node[max(s.nodes())]['cpostag'] == 'PUNCT':
if verbroot:
T.add((verbroot,max(s.nodes())))
elif adjroot:
T.add((adjroot,max(s.nodes())))
scorerdict["PUNCT"].append(get_scores(T,goldedgeset))
T = set()
scorerdict["__TOTAL"].append(get_scores(D,goldedgeset))
ausgraph = nx.DiGraph()
ausgraph.add_nodes_from(list(s.nodes()))
ausgraph.add_edges_from(D)
for n in s.nodes()[1:]:
if not ausgraph.predecessors(n): # if n has no head
ausgraph.add_edge(n,n)
s.remove_edges_from(s.edges())
if ausgraph.successors(0):
mainpred = ausgraph.successors(0)[0]
else:
mainpred = 0
for h,d in ausgraph.edges():
label = "dep"
if h == 0:
label = "root"
elif h == d:
label = 'backoff'
if backoff == 'cycle':
h = d
elif backoff == 'left':
if d == 1:
h = mainpred
else:
h = d -1
elif backoff == 'right':
if d == max(s.nodes()):
h = mainpred
else:
h = d + 1
s.add_edge(h,d,{'deprel' : label})
return s
def add_all_edges(s):
#connect each word wwith w+1 and w-1
#this ensures connectedness
for h in s.nodes():
for d in s.nodes():<|fim▁hole|>def manage_function_words(s):
"""such as reducing their predisposition to be heads"""
for h in [x for x in s.nodes() if s.node[x]['cpostag'] in OPEN]:
for d in [x for x in s.nodes()[h-3:h+3] if s.node[x]['cpostag'] in CLOSED]:
if h != d:
s.add_edge(h,d)
return s
def relate_content_words(s):
for h in [x for x in s.nodes() if s.node[x]['cpostag'] in OPEN]:
for d in [x for x in s.nodes() if s.node[x]['cpostag'] in OPEN and x !=h]:
s.add_edge(h,d)
return s
def attach_adjacent(s,direction):
s.remove_edges_from(s.edges())
if direction == 'left':
for n in s.nodes()[1:]:
s.add_edge(n-1,n,{'deprel' : 'backoff'})
else:
s.add_edge(0,s.nodes()[-1],{'deprel' : 'backoff'})
for n in s.nodes()[1:-1]:
s.add_edge(n+1,n,{'deprel' : 'backoff'})
return s
def add_all_edges(s):
#connect each word wwith w+1 and w-1
#this ensures connectedness
for h in s.nodes():
for d in s.nodes():
if h != d:
s.add_edge(h,d)
return s
def add_short_edges(s):
#connect each word wwith w+1 and w-1
#this ensures connectedness
for n in s.nodes():
if n+1 in s.nodes():
s.add_edge(n+1,n)
if n-1 in s.nodes():
s.add_edge(n-1,n)
return s
def add_head_rule_edges(s,headrules):
for h in s.nodes():
for d in [x for x in s.nodes() if x!=h]:
pos_h = s.node[h]['cpostag']
pos_d = s.node[d]['cpostag']
if not headrules[(headrules["head"]==pos_h) & (headrules["dep"]==pos_d)].empty:
s.add_edge(h,d)
return s
def morphological_inequality():
#if two words have different prefixes or suffixes, we add an edge between them
#How to relate this to UD morphofeats if available?
return
def add_verb_edges(s):
#all words are attached to all VERB-type words
#we add all nouns to verbs i.e. NOUN and PROPN
ALLVERBS = [n for n in s.nodes() if s.node[n]['cpostag']=='VERB']
ALLNOUNS = [n for n in s.nodes() if s.node[n]['cpostag']=='NOUN' or s.node[n]['cpostag']=='PROPN' ]
for n in s.nodes():
for v in ALLVERBS:
s.add_edge(v,n) # all words are dependent on verbs
if n in ALLNOUNS: #nouns are 2x dependent on verbs
s.add_edge(v,n)
return s
def tree_decoding_algorithm_content_and_function(s,headrules,reverse=True,ablation='pagerank'):
#This is the algorithm in Fig 3 in Søgaard(2012).
if ablation == 'pagerank':
rankedindices = [x for x in s.nodes()]
else:
personalization = dict(
[[x, 1] for x in s.nodes() if s.node[x]['cpostag'] in CONTENT] + [[x, 1] for x in s.nodes() if
s.node[x]['cpostag'] not in CONTENT])
ALLVERBS = sorted([n for n in s.nodes() if s.node[n]['cpostag'] == 'VERB'])
ALLCONTENT = sorted([n for n in s.nodes() if s.node[n]['cpostag'] in CONTENT])
if ALLVERBS:
personalization[ALLVERBS[0]] = 5
elif ALLCONTENT:
personalization[ALLCONTENT[0]] = 5
if reverse:
rev_s = nx.reverse(nx.DiGraph(s))
else:
rev_s = nx.DiGraph(s)
rankdict = nx.pagerank_numpy(rev_s, alpha=0.95, personalization=personalization)
rankedindices = [k for k, v in Counter(rankdict).most_common()]
H = set()
D = set()
contentindices = [x for x in rankedindices if s.node[x]['cpostag'] in CONTENT]
functionindices = [x for x in rankedindices if x not in contentindices]
print(contentindices)
for i in contentindices: #We attach elements from highest to lowest, i.e. the word with the highest PR will be the dependent of root
if len(H) == 0:
n_j_prime = 0
else:
n_j_prime_index_headrules = None
POS_i = s.node[i]['cpostag']
possible_headsin_table = list(headrules[headrules['dep']==POS_i]['head'].values)
H_headrules = [h for h in H if s.node[h]['cpostag'] in possible_headsin_table]
if H_headrules:
n_j_prime_index_headrules = np.argmin([abs(i - j) for j in sorted(H_headrules)]) #find the head of i
n_j_prime=sorted(H_headrules)[n_j_prime_index_headrules]
if not n_j_prime_index_headrules:
n_j_prime_index = np.argmin([abs(i - j) for j in sorted(H)]) #find the head of i
n_j_prime=sorted(H)[n_j_prime_index]
D.add((n_j_prime,i))
H.add(i)
s.node[i]['lemma']=str(rankedindices.index(i))
for i in functionindices: #We attach elements from highest to lowest, i.e. the word with the highest PR will be the dependent of root
if len(H) == 0:
n_j_prime = 0
else:
n_j_prime_index_headrules = None
POS_i = s.node[i]['cpostag']
possible_headsin_table = list(headrules[headrules['dep']==POS_i]['head'].values)
if POS_i in RIGHTATTACHING:# ["ADP","DET","AUX","SCONJ"]:
H_headrules = [h for h in H if s.node[h]['cpostag'] in possible_headsin_table and h > i]
elif POS_i in LEFTATTACHING:
H_headrules = [h for h in H if s.node[h]['cpostag'] in possible_headsin_table and h < i]
else:
H_headrules = [h for h in H if s.node[h]['cpostag'] in possible_headsin_table]
if H_headrules:
n_j_prime_index_headrules = np.argmin([abs(i - j) for j in sorted(H_headrules)]) #find the head of i
n_j_prime=sorted(H_headrules)[n_j_prime_index_headrules]
else:
#if not n_j_prime_index_headrules:
n_j_prime_index = np.argmin([abs(i - j) for j in sorted(H)]) #find the head of i
n_j_prime=sorted(H)[n_j_prime_index]
D.add((n_j_prime,i))
s.node[i]['lemma']=str(rankedindices.index(i))
s.add_node(0,attr_dict={'form' :'ROOT', 'lemma' :'ROOT', 'cpostag' :'ROOT', 'postag' : 'ROOT'})
s.remove_edges_from(s.edges())
s.add_edges_from(D)
#Make sure there are no full 0-attached sentences sentences
mainpred = sorted(s.successors(0))[0]
if len(s.successors(0)) > 1:
for other in sorted(s.successors(0))[1:]:
s.remove_edge(0,other)
s.add_edge(mainpred,other)
if s.node[max(s.nodes())]['cpostag'] == 'PUNCT':
lastperiod = max(s.nodes())
s.remove_edge(s.head_of(lastperiod),lastperiod)
s.add_edge(mainpred,lastperiod)
if s.node[1]['cpostag'] == 'PUNCT':
s.remove_edge(s.head_of(1),1)
s.add_edge(mainpred,1)
for h,d in s.edges():
s[h][d]['deprel'] = 'root' #if h == 0 else 'dep'
return s
def tree_decoding_algorithm(s,headrules):
#This is the algorithm in Fig 3 in Søgaard(2012).
#TODO reconsider root-attachment after first iteration, it is non-UD
personalization = dict([[x,1] for x in s.nodes() if s.node[x]['cpostag'] in OPEN]+[[x,1] for x in s.nodes() if s.node[x]['cpostag'] not in OPEN])
rankdict = nx.pagerank_numpy(s,alpha=0.95,personalization=personalization)
rankedindices=[k for k,v in Counter(rankdict).most_common()]
pi = rankedindices
H = set()
D = set()
for i in rankedindices: #We attach elements from highest to lowest, i.e. the word with the highest PR will be the dependent of root
if len(H) == 0:
n_j_prime = 0
else:
n_j_prime_index_headrules = None
if not headrules.empty:
POS_i = s.node[i]['cpostag']
possible_headsin_table = list(headrules[headrules['dep']==POS_i]['head'].values)
H_headrules = [h for h in H if s.node[h]['cpostag'] in possible_headsin_table]
if H_headrules:
n_j_prime_index_headrules = np.argmin([abs(i - j) for j in sorted(H_headrules)]) #find the head of i
n_j_prime=sorted(H_headrules)[n_j_prime_index_headrules]
if not n_j_prime_index_headrules:
n_j_prime_index = np.argmin([abs(i - j) for j in sorted(H)]) #find the head of i
n_j_prime=sorted(H)[n_j_prime_index]
D.add((n_j_prime,i))
if onlycontentheads and s.node[i]['cpostag'] in OPEN: #we only allow content words to be heads
H.add(i)
s.node[i]['lemma']=str(rankedindices.index(i))
s.add_node(0,attr_dict={'form' :'ROOT', 'lemma' :'ROOT', 'cpostag' :'ROOT', 'postag' : 'ROOT'})
s.remove_edges_from(s.edges())
s.add_edges_from(D)
for h,d in s.edges():
s[h][d]['deprel'] = 'root' if h == 0 else 'dep'
return s
def main():
parser = argparse.ArgumentParser(description="""Convert conllu to conll format""")
parser.add_argument('--input', help="conllu file", default='../data/en-ud-dev.conllu')
parser.add_argument('--lang')
parser.add_argument('--posrules', help="head POS rules file", default='../data/posrules.tsv')
parser.add_argument('--output', help="target file",default="testout.conllu")
parser.add_argument('--parsing_strategy', choices=['rules','pagerank','adjacent'],default='pagerank')
parser.add_argument('--steps', choices=['twotags','complete','neighbors','verbs','function','content','headrule'], nargs='+', default=[""])
parser.add_argument('--reverse', action='store_true',default=True)
parser.add_argument('--rule_backoff', choices=['cycle','left','right'],default="left")
parser.add_argument('--ablation', choices=['pagerank','2stepdecoding'],default="pagerank")
args = parser.parse_args()
if sys.version_info < (3,0):
print("Sorry, requires Python 3.x.") #suggestion: install anaconda python
sys.exit(1)
headrules = pd.read_csv(args.posrules,'\t')
cio = CoNLLReader()
orig_treebank = cio.read_conll_u(args.input)
ref_treebank = cio.read_conll_u(args.input)
modif_treebank = []
posbigramcounter,wordcounter = count_pos_bigrams(orig_treebank)
functionlist = [x for x,y in wordcounter.most_common(100)]
print(functionlist)
fill_out_left_and_right_attach(posbigramcounter)
if args.parsing_strategy == 'pagerank':
for o,ref in zip(orig_treebank,ref_treebank):
s = copy.copy(o)
s.remove_edges_from(s.edges())
s.remove_node(0) # From here and until tree reconstruction there is no symbolic root node, makes our life a bit easier
if "twotags" in args.steps:
s = map_to_two_tags(s,functionlist)
if "complete" in args.steps:
s = add_all_edges(s)
if "neighbors" in args.steps:
s = add_short_edges(s)
if "verbs" in args.steps:
s = add_verb_edges(s)
if "function" in args.steps:
s = manage_function_words(s)
if "content" in args.steps:
s = relate_content_words(s)
if "headrule" in args.steps:
s = add_head_rule_edges(s,headrules)
tree_decoding_algorithm_content_and_function(s,headrules,args.reverse,args.ablation)
modif_treebank.append(s)
if args.reverse:
r = ".rev"
else:
r = ".norev"
outfile = Path(args.lang+"_"+args.output +"_"+ "_".join(args.steps)+r+".conllu")
cio.write_conll(modif_treebank,outfile,conllformat='conllu', print_fused_forms=False,print_comments=False)
outfile = Path(args.lang+"_"+args.output)
cio.write_conll(modif_treebank,outfile,conllformat='conllu', print_fused_forms=False,print_comments=False)
elif args.parsing_strategy == 'adjacent':
for s in orig_treebank:
s.remove_edges_from(s.edges())
s = attach_adjacent(s,args.rule_backoff)
modif_treebank.append(s)
outfile = Path(args.output +"."+args.rule_backoff)
cio.write_conll(modif_treebank,outfile,conllformat='conllu', print_fused_forms=False,print_comments=False)
else:
for s in orig_treebank:
s = add_high_confidence_edges(s,posbigramcounter,args.rule_backoff)
modif_treebank.append(s)
for k in sorted(scorerdict.keys()):
prec = sum([p for p,r in scorerdict[k]]) / len(scorerdict[k])
reca = sum([r for p,r in scorerdict[k]]) / len(scorerdict[k])
print('{0}, {1:.2f}, {2:.2f}'.format(k, prec, reca))
outfile = Path(args.output +".rules")
cio.write_conll(modif_treebank,outfile,conllformat='conllu', print_fused_forms=False,print_comments=False)
if __name__ == "__main__":
main()<|fim▁end|> | if h != d:
s.add_edge(h,d)
return s
|
<|file_name|>config.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
basedir=os.path.abspath(os.path.dirname(__file__))#get basedir of the project
WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-guess'
#for database
# SQLALCHEMY_DATABASE_URI = 'mysql:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_DATABASE_URI = "mysql://username:password@server_ip:port/database_name"
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')<|fim▁hole|>
#for upload pic
UPLOAD_FOLDER = basedir+'/uploads/' #should use basedir
MAX_CONTENT_LENGTH=2*1024*1024
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])#TODO:make user aware
#for upload excel
UPLOAD_EXCEL = basedir+'/app/static/add_info/' #should use basedir<|fim▁end|> | |
<|file_name|>clarify_brightcove_bridge.py<|end_file_name|><|fim▁begin|>from collections import Counter<|fim▁hole|>MAX_METADATA_STRING_LEN = 2000
def default_to_empty_string(val):
return val if val is not None else ''
class ClarifyBrightcoveBridge:
def __init__(self, clarify_client, bc_client):
self.clarify_client = clarify_client
self.bc_client = bc_client
self.sync_stats = Counter(created=0, updated=0, deleted=0)
self.dry_run = False
def log(self, output_str):
print(output_str)
def log_sync_stats(self):
print('\nBundle stats:')
print(' created: {0}'.format(self.sync_stats['created']))
print(' updated: {0}'.format(self.sync_stats['updated']))
print(' deleted: {0}'.format(self.sync_stats['deleted']))
print(' total: {0}'.format(self.sync_stats['count']))
def _load_bundle_map(self):
'''
Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contains the Brightcove video id.
'''
bundle_map = {}
next_href = None
has_next = True
while has_next:
bundles = self.clarify_client.get_bundle_list(href=next_href, embed_items=True)
items = get_embedded_items(bundles)
for item in items:
bc_video_id = item.get('external_id')
if bc_video_id is not None and len(bc_video_id) > 0:
bundle_map[bc_video_id] = item
next_href = get_link_href(bundles, 'next')
if next_href is None:
has_next = False
return bundle_map
def _metadata_from_video(self, video):
'''Generate the searchable metadata that we'll store in the bundle for the video'''
long_desc = video['long_description']
if long_desc is not None:
long_desc = long_desc[:MAX_METADATA_STRING_LEN]
tags = video.get('tags')
metadata = {
'name': default_to_empty_string(video.get('name')),
'description': default_to_empty_string(video.get('description')),
'long_description': default_to_empty_string(long_desc),
'tags': tags if tags is not None else [],
'updated_at': video.get('updated_at'),
'created_at': video.get('created_at'),
'state': video.get('state')
}
return metadata
def _src_media_url_for_video(self, video):
'''Get the url for the video media that we can send to Clarify'''
src_url = None
best_height = 0
best_source = None
# TODO: This assumes we have ingested videos. For remote videos, check if the remote flag is True
# and if so, use the src url from the Asset endpoint.
video_sources = self.bc_client.get_video_sources(video['id'])
# Look for codec H264 with good resolution
for source in video_sources:
height = source.get('height', 0)
codec = source.get('codec')
if source.get('src') and codec and codec.upper() == 'H264' and height <= 1080 and height > best_height:
best_source = source
if best_source is not None:
src_url = best_source['src']
return src_url
def _create_bundle_for_video(self, video):
media_url = self._src_media_url_for_video(video)
if not media_url:
self.log('SKIPPING: No suitable video src url for video {0} {1}'.format(video['id'], video['name']))
return
self.log('Creating bundle for video {0} {1}'.format(video['id'], video['name']))
if not self.dry_run:
external_id = video['id']
name = video.get('original_filename')
metadata = self._metadata_from_video(video)
self.clarify_client.create_bundle(name=name, media_url=media_url,
metadata=metadata, external_id=external_id)
self.sync_stats['created'] += 1
def _update_metadata_for_video(self, metadata_href, video):
'''
Update the metadata for the video if video has been updated in Brightcove since the bundle
metadata was last updated.
'''
current_metadata = self.clarify_client.get_metadata(metadata_href)
cur_data = current_metadata.get('data')
if cur_data.get('updated_at') != video['updated_at']:
self.log('Updating metadata for video {0}'.format(video['id']))
if not self.dry_run:
metadata = self._metadata_from_video(video)
self.clarify_client.update_metadata(metadata_href, metadata=metadata)
self.sync_stats['updated'] += 1
def sync_bundles(self, delete_bundles=True, update_metadata=True, confirm_delete_fun=None, dry_run=False):
self.dry_run = dry_run
self.sync_stats.clear()
if dry_run:
self.log('-----------------------------------')
self.log('DRY RUN - not modifying any bundles')
self.log('-----------------------------------')
self.log('Fetching bundles...')
bundle_map = self._load_bundle_map()
self.log('Fetching videos...')
videos = self.bc_client.get_all_videos()
self.log('Checking {0} videos...'.format(len(videos)))
for video in videos:
vid = video['id']
bundle = bundle_map.get(vid)
if bundle is None:
# Create a bundle for the video
self._create_bundle_for_video(video)
elif update_metadata:
# Update the metadata in the bundle for the video
self._update_metadata_for_video(get_link_href(bundle, 'clarify:metadata'), video)
if delete_bundles:
self.log('Checking deleted videos...')
# Delete bundles for missing videos
existing_vids = set([x['id'] for x in videos])
existing_bundles = set(bundle_map.keys())
missing_bundles = existing_bundles - existing_vids
if len(missing_bundles):
for vid in missing_bundles:
bundle = bundle_map.get(vid)
if dry_run or confirm_delete_fun is None or \
confirm_delete_fun(bundle['name'], bundle['external_id']):
self.log('Delete bundle for video {0}'.format(bundle['external_id']))
if not dry_run:
self.clarify_client.delete_bundle(get_link_href(bundle, 'self'))
self.sync_stats['deleted'] += 1
self.sync_stats['count'] = len(bundle_map) + self.sync_stats['created'] - self.sync_stats['deleted']
self.log('done.')<|fim▁end|> | from clarify_python.helper import get_embedded_items, get_link_href
|
<|file_name|>0026_add_access_control_tables.py<|end_file_name|><|fim▁begin|>from redash.models import db, Change, AccessPermission, Query, Dashboard
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
if not Change.table_exists():
Change.create_table()
if not AccessPermission.table_exists():
AccessPermission.create_table()
migrator = PostgresqlMigrator(db.database)
<|fim▁hole|> )
except Exception as ex:
print "Error while adding version column to queries/dashboards. Maybe it already exists?"
print ex<|fim▁end|> | try:
migrate(
migrator.add_column('queries', 'version', Query.version),
migrator.add_column('dashboards', 'version', Dashboard.version) |
<|file_name|>xmlwitch.py<|end_file_name|><|fim▁begin|>from __future__ import with_statement
import sys
from xml.sax import saxutils
from keyword import kwlist as PYTHON_KWORD_LIST
is_py2 = sys.version[0] == '2'
if is_py2:
from StringIO import StringIO
else:
from io import StringIO
__all__ = ['Builder', 'Element']
__license__ = 'BSD'
__version__ = '0.2.1'
__author__ = "Jonas Galvez <http://jonasgalvez.com.br/>"
__contributors__ = ["bbolli <http://github.com/bbolli/>",
"masklinn <http://github.com/masklinn/>"]
class Builder:
def __init__(self, encoding='utf-8', indent=' '*2, version=None):
self._document = StringIO()
self._encoding = encoding
self._indent = indent
self._indentation = 0
if version is not None:
self.write('<?xml version="%s" encoding="%s"?>\n' % (
version, encoding
))
def __getattr__(self, name):
return Element(name, self)
def __getitem__(self, name):
return Element(name, self)
def __str__(self):
if is_py2:
return self._document.getvalue().encode(self._encoding).strip()
else:
return self._document.getvalue()
def __unicode__(self):
if is_py2:
return self._document.getvalue().decode(self._encoding).strip()
else:
return self._document.getvalue()
def write(self, content):
"""Write raw content to the document"""
if is_py2 and type(content) is not unicode:
content = content.decode(self._encoding)
self._document.write('%s' % content)
def write_escaped(self, content):
"""Write escaped content to the document"""
self.write(saxutils.escape(content))
def write_indented(self, content):
"""Write indented content to the document"""
self.write('%s%s\n' % (self._indent * self._indentation, content))
builder = Builder # 0.1 backward compatibility
class Element:
PYTHON_KWORD_MAP = dict([(k + '_', k) for k in PYTHON_KWORD_LIST])
def __init__(self, name, builder):
self.name = self._nameprep(name)
self.builder = builder
self.attributes = {}
def __enter__(self):
"""Add a parent element to the document"""
self.builder.write_indented('<%s%s>' % (
self.name, self._serialized_attrs()
))
self.builder._indentation += 1
return self
def __exit__(self, type, value, tb):
"""Add close tag to current parent element"""
self.builder._indentation -= 1
self.builder.write_indented('</%s>' % self.name)
def __call__(*args, **kargs):
"""Add a child element to the document"""
self = args[0]
self.attributes.update(kargs)
if len(args) > 1:
value = args[1]
if value is None:
self.builder.write_indented('<%s%s />' % (
self.name, self._serialized_attrs()
))
else:
value = saxutils.escape(value)
self.builder.write_indented('<%s%s>%s</%s>' % (
self.name, self._serialized_attrs(), value, self.name
))
return self
def _serialized_attrs(self):
"""Serialize attributes for element insertion"""
serialized = []
for attr, value in self.attributes.items():
serialized.append(' %s=%s' % (
self._nameprep(attr), saxutils.quoteattr(value)
))
return ''.join(serialized)
<|fim▁hole|> return name.replace('__', ':')<|fim▁end|> |
def _nameprep(self, name):
"""Undo keyword and colon mangling"""
name = Element.PYTHON_KWORD_MAP.get(name, name)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from jupyter_server.utils import url_path_join as ujoin
from .config import Lmod as LmodConfig
from .handler import default_handlers, PinsHandler
def _jupyter_server_extension_paths():
return [{"module": "jupyterlmod"}]
# Jupyter Extension points
def _jupyter_nbextension_paths():
return [
dict(
section="tree", src="static", dest="jupyterlmod", require="jupyterlmod/main"
)
]
def load_jupyter_server_extension(nbapp):
"""
Called when the extension is loaded.
Args:
nbapp : handle to the Notebook webserver instance.
"""<|fim▁hole|>
web_app = nbapp.web_app
base_url = web_app.settings["base_url"]
for path, class_ in default_handlers:
web_app.add_handlers(".*$", [(ujoin(base_url, path), class_)])
web_app.add_handlers(".*$", [
(ujoin(base_url, 'lmod/launcher-pins'), PinsHandler, {'launcher_pins': launcher_pins}),
])<|fim▁end|> | nbapp.log.info("Loading lmod extension")
lmod_config = LmodConfig(parent=nbapp)
launcher_pins = lmod_config.launcher_pins |
<|file_name|>people_fr_CA.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="fr_CA" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About People</source>
<translation>Au sujet de People</translation>
</message>
<message>
<location line="+39"/>
<source><b>People</b> version</source>
<translation>Version de <b>People</b></translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014-%1 The People developers</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014-[CLIENT_LAST_COPYRIGHT] The People developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:[email protected]">[email protected]</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+218"/>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>pubkey</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>stealth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<location line="+4"/>
<source>Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>n/a</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialogue de phrase de passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Saisir la phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nouvelle phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Répéter la phrase de passe</translation>
</message>
<message>
<location line="+33"/>
<location line="+16"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Sert à désactiver les transactions sortantes si votre compte de système d'exploitation est compromis. Ne procure pas de réelle sécurité.</translation>
</message>
<message>
<location line="-13"/>
<source>For staking only</source>
<translation>Pour "staking" seulement</translation>
</message>
<message>
<location line="+16"/>
<source>Enable messaging</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+39"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Saisir la nouvelle phrase de passe pour le portefeuille. <br/>Veuillez utiliser une phrase de passe de <b>10 caractères aléatoires ou plus</b>, ou de <b>huit mots ou plus</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Crypter le portefeuille</translation>
</message>
<message>
<location line="+11"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déverrouiller le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Déverrouiller le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déchiffrer le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Déchiffrer le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Changer la phrase de passe</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Saisir l’ancienne et la nouvelle phrase de passe du portefeuille</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Confirmer le cryptage du portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>ATTENTION : Si vous cryptez votre portefeuille et perdez votre passphrase, vous ne pourrez plus accéder à vos People</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Êtes-vous sûr de vouloir crypter votre portefeuille ?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT : Toute sauvegarde précédente de votre fichier de portefeuille devrait être remplacée par le nouveau fichier de portefeuille crypté. Pour des raisons de sécurité, les sauvegardes précédentes de votre fichier de portefeuille non crypté deviendront inutilisables dès lors que vous commencerez à utiliser le nouveau portefeuille crypté.</translation>
</message>
<message>
<location line="+104"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Attention : la touche Verr. Maj. est activée !</translation>
</message>
<message>
<location line="-134"/>
<location line="+61"/>
<source>Wallet encrypted</source>
<translation>Portefeuille crypté</translation>
</message>
<message>
<location line="-59"/>
<source>People will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>L'application People va désormais se terminer afin de finaliser le processus de cryptage. Merci de noter que le cryptage du portefeuille ne garantit pas de se prémunir du vol via l'utilisation de malware, qui auraient pu infecter votre ordinateur. </translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+45"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Le cryptage du portefeuille a échoué</translation>
</message>
<message>
<location line="-57"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Le cryptage du portefeuille a échoué en raison d'une erreur interne. Votre portefeuille n'a pas été crypté.</translation>
</message>
<message>
<location line="+7"/>
<location line="+51"/>
<source>The supplied passphrases do not match.</source>
<translation>Les phrases de passe saisies ne correspondent pas.</translation>
</message>
<message>
<location line="-39"/>
<source>Wallet unlock failed</source>
<translation>Le déverrouillage du portefeuille a échoué</translation>
</message>
<message>
<location line="+1"/>
<location line="+13"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La phrase de passe saisie pour décrypter le portefeuille était incorrecte.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Le décryptage du portefeuille a échoué</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La phrase de passe du portefeuille a été modifiée avec succès.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+137"/>
<source>Network Alert</source>
<translation>Alerte réseau</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Fonctions de contrôle des monnaies</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Quantité :</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Octets :</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Priorité :</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Sortie faible :</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+528"/>
<location line="+30"/>
<source>no</source>
<translation>non</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Après les frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Monnaie :</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Tout (dé)sélectionner</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Mode arborescence</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Mode liste</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Intitulé</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmations</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Priorité</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-520"/>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copier la quantité</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copier les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copier le montant après les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copier les octets</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copier la priorité</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copier la sortie faible</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copier la monnaie</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>la plus élevée</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>élevée</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>moyennement-élevée</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>moyenne</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>moyennement-basse</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>basse</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>la plus basse</translation>
</message>
<message>
<location line="+130"/>
<location line="+30"/>
<source>DUST</source>
<translation>DUST</translation>
</message>
<message>
<location line="-30"/>
<location line="+30"/>
<source>yes</source>
<translation>oui</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Cet intitulé passe au rouge, si la taille de la transaction est supérieure à 10000 bytes.
Cela implique que des frais à hauteur d'au moins %1 par kb seront nécessaires.
Ceux-ci Peuvent varier de +/- 1 Byte par entrée.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Les transactions avec une priorité haute ont plus de chances d'être traitées en un block.
Rouge si votre priorité est plus petite que "moyenne".
Cela veut dire que des frais d'un minimum de %1 par kb sont requis</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Ce label passe au rouge, Lorsqu'un destinataire reçoit un montant inférieur à %1.
Cela implique que des frais à hauteur de %2 seront nécessaire
Les montants inférieurs à 0.546 fois les frais minimum de relais apparaissent en tant que DUST.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Ce label passe au rouge, lorsque la différence est inférieure à %1.
Cela implique que des frais à hauteur d'au moins %2 seront nécessaires.</translation>
</message>
<message>
<location line="+40"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>monnaie de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(monnaie)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Modifier l'adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Étiquette</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>L'intitulé associé à cette entrée du carnet d'adresse</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>L'intitulé associé à cette entrée du carnet d'adresse. Seules les adresses d'envoi peuvent être modifiées.</translation>
</message>
<message>
<location line="+7"/>
<source>&Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Nouvelle adresse de réception</translation>
</message>
<message>
<location line="+7"/>
<source>New sending address</source>
<translation>Nouvelle adresse d’envoi</translation>
</message>
<message>
<location line="+4"/>
<source>Edit receiving address</source>
<translation>Modifier l’adresse de réception</translation>
</message>
<message>
<location line="+7"/>
<source>Edit sending address</source>
<translation>Modifier l’adresse d'envoi</translation>
</message>
<message>
<location line="+82"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>L’adresse fournie « %1 » est déjà présente dans le carnet d'adresses.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid People address.</source>
<translation>L'adresse "%1" renseignée n'est pas une adresse People valide.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossible de déverrouiller le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Échec de génération de la nouvelle clef.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+526"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+0"/>
<location line="+12"/>
<source>People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Usage:</source>
<translation>Utilisation:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Options graphiques</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Définir la langue, par exemple « fr_FR » (par défaut : la langue du système)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Démarrer en mode réduit</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Affichage de l'écran de démarrage (défaut: 1)</translation>
</message>
</context>
<context>
<name>MessageModel</name>
<message>
<location filename="../messagemodel.cpp" line="+376"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Sent Date Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Received Date Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>To Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>From Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send Secure Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send failed: %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+1"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start people: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<location filename="../peertablemodel.cpp" line="+118"/>
<source>Address/Hostname</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../guiutil.cpp" line="-470"/>
<source>%1 d</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+55"/>
<source>%1 s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>None</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>%1 ms</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nom du client</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+23"/>
<location line="+491"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<source>N/A</source>
<translation>N.D.</translation>
</message>
<message>
<location line="-1062"/>
<source>Client version</source>
<translation>Version du client</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informations</translation>
</message>
<message>
<location line="-10"/>
<source>People - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>People Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Using OpenSSL version</source>
<translation>Version d'OpenSSL utilisée</translation>
</message>
<message>
<location line="+26"/>
<source>Using BerkeleyDB version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Heure de démarrage</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Réseau</translation>
</message>
<message>
<location line="+7"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Number of connections</source>
<translation>Nombre de connexions</translation>
</message>
<message>
<location line="+157"/>
<source>Show the People help message to get a list with possible People command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+99"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<location filename="../rpcconsole.cpp" line="+396"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<location filename="../rpcconsole.cpp" line="+1"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>&Peers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<location filename="../rpcconsole.cpp" line="-167"/>
<location line="+328"/>
<source>Select a peer to view detailed information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Peer ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Direction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Services</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Starting Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Sync Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ban Score</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Connection Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Sent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Received</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Time Offset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-866"/>
<source>Block chain</source>
<translation>Chaîne de blocks</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nombre actuel de blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Nombre total estimé de blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Horodatage du dernier block</translation>
</message>
<message>
<location line="+49"/>
<source>Open the People debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Open</source>
<translation>&Ouvrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+10"/>
<source>&Show</source>
<translation>&Afficher</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-266"/>
<source>Build date</source>
<translation>Date de compilation</translation>
</message>
<message>
<location line="+206"/>
<source>Debug log file</source>
<translation>Journal de débogage</translation>
</message>
<message>
<location line="+109"/>
<source>Clear console</source>
<translation>Nettoyer la console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-197"/>
<source>Welcome to the People Core RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utiliser les touches de curseur pour naviguer dans l'historique et <b>Ctrl-L</b> pour effacer l'écran.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Taper <b>help</b> pour afficher une vue générale des commandes disponibles.</translation>
</message>
<message>
<location line="+233"/>
<source>via %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+1"/>
<source>never</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Inbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Outbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Unknown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+1"/>
<source>Fetching...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeopleBridge</name>
<message>
<location filename="../peoplebridge.cpp" line="+410"/>
<source>Incoming Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source><b>%1</b> to PEOPLE %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source><b>%1</b> PEOPLE, ring size %2 to PEOPLE %3 (%4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source><b>%1</b> PEOPLE, ring size %2 to MEN %3 (%4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<location line="+10"/>
<location line="+12"/>
<location line="+8"/>
<source>Error:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Unknown txn type detected %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Input types must match for all recipients.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Ring sizes must match for all recipients.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Ring size outside range [%1, %2].</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<location line="+9"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Are you sure you want to send?
Ring size of one is not anonymous, and harms the network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+9"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<location line="+25"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>The change address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<location line="+376"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-371"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+365"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-360"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Narration is too long.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Ring Size Error.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Input Type Error.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Must be in full mode to send anon.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Invalid Stealth Address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your people balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error generating transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error generating transaction: %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+304"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>The message can't be empty.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Error: Message creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The message was rejected.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+98"/>
<source>Sanity Error!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: a sanity check prevented the transfer of a non-group private key, please close your wallet and report this error to the development team as soon as possible.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bridgetranslations.h" line="+8"/>
<source>Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Notifications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Management</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add New Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Import Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Advanced</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change Passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(Un)lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Tools</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chain Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Block Explorer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Debug</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>About People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>About QT</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>QR code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Narration:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>MEN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>WOMEN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>µMEN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Peoplehi</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add new receive address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Add Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add a new contact</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Lookup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Normal</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Stealth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>BIP32</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Public Key</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction Hash</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recent Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Market</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Advanced Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Make payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balance transfer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>LowOutput:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>From account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>PUBLIC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>PRIVATE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Ring Size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>To account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Pay to</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+135"/>
<source>Tor connection offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>i2p connection offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet is encrypted and currently locked</source>
<translation type="unfinished"/>
</message>
<message>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open chat list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Values</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Outputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a PeopleCash address to sign the message with (e.g. SaKYqfD8J3vw4RTnqtgk2K9B67CBaL3mhV)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the message you want to sign</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Click sign message to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy the signed message signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a PeopleCash address to verify the message with (e.g. SaKYqfD8J3vw4RTnqtgk2K9B67CBaL3mhV)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the message you want to verify</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a PeopleCash signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Paste signature from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balances overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recent in/out transactions or stakes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select inputs to spend</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Optional address to receive transaction change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Current spendable send payment balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Current spendable balance to account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>The address to transfer the balance to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The label for this address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount to transfer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Double click to edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Short payment note.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The address to send the payment to (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a public key for the address above</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Name for this Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a password</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Would you like to create a bip44 path?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your recovery phrase (Keep this safe!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Make Default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Activate/Deactivate</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set as Master</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>0 active connections to People network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>The address to send the payment to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a short note to send with payment (max 24 characters)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Wallet Name for recovered account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the password for the wallet you are trying to recover</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Is this a bip44 path?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-66"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-122"/>
<source>Narration</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Default Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Clear All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Suggest Ring Size</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RECEIVE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Filter by type..</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>TRANSACTIONS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ADDRESSBOOK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Private Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Name:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Public Key:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose identity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Identity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Group Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Group name:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Create Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite others</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite others to group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite to Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>GROUP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>BOOK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start private conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start group conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>CHAT</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Leave Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>CHAIN DATA</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Coin Value</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Owned (Mature)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>System (Mature)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Spends</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Least Depth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>BLOCK EXPLORER</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Refresh</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Hash</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Value Out</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>OPTIONS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>I2P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Tor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start People on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Pay transaction fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Most transactions are 1kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enable Staking</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Reserve:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimum Stake Interval</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimum Ring size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum Ring size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Automatically select ring size</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enable Secure messaging</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Mode (Requires Restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Full Index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Index Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Map port using UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Proxy IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>SOCKS Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>User Interface language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rows per page:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Notifications:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Visible Transaction Types:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>I2P (coming soon)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>TOR (coming soon)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Ok</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lets create a New Wallet and Account to get you started!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Password</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add an optional Password to secure the Recovery Phrase (shown on next page)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Would you like to create a Multi-Account HD Key? (BIP44)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Language</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>English</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>French</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Japanese</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Spanish</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chinese (Simplified)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chinese (Traditional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Next Step</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Write your Wallet Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Important!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/><|fim▁hole|> <translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Back</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Please confirm your Wallet Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Congratulations! You have successfully created a New Wallet and Account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You can now use your Account to send and receive funds :)
Remember to keep your Wallet Recovery Phrase and Password (if set) safe in case you ever need to recover your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Lets import your Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The Wallet Recovery Phrase could require a password to be imported</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Is this a Multi-Account HD Key (BIP44)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recovery Phrase (Usually 24 words)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Congratulations! You have successfully imported your Wallet from your Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You can now use your Account to send and receive funds :)
Remember to keep your Wallet Recovery Phrase and Password safe in case you ever need to recover your wallet again!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Accounts</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Created</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Active Account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Keys</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Path</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Active</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Master</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeopleGUI</name>
<message>
<location filename="../people.cpp" line="+111"/>
<source>A fatal error occurred. People can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../peoplegui.cpp" line="+89"/>
<location line="+178"/>
<source>Hpeople</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-178"/>
<source>Client</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&About People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Modify configuration options for People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+74"/>
<source>Hpeople client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+63"/>
<source>%n active connection(s) to People network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>header</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>headers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<location line="+22"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Downloading filtered blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>~%1 filtered block(s) remaining (%2% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Importing blocks...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+5"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+13"/>
<location line="+4"/>
<source>Imported</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<location line="+4"/>
<source>Downloaded</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-3"/>
<source>%1 of %2 %3 of transaction history (%4% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>%1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+23"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+3"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+7"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Last received %1 was generated %2.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<location line="+15"/>
<source>Incoming Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
From Address: %2
To Address: %3
Message: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid People address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking and messaging only.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for messaging only.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet must first be encrypted to be locked.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+69"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+9"/>
<source>Staking.
Your weight is %1
Network weight is %2
Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Not staking because wallet is in thin mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking, staking is disabled</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactionrecord.cpp" line="+23"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received people</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent people</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+79"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Ouvert pour %n bloc</numerusform><numerusform>Ouvert pour %n blocks</numerusform></translation>
</message>
<message>
<location line="+7"/>
<source>conflicted</source>
<translation>en conflit</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/hors ligne</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/non confirmée</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>État</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, diffusée à travers %n nœud</numerusform><numerusform>, diffusée à travers %n nœuds</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Généré</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<location line="+20"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="-19"/>
<location line="+20"/>
<location line="+23"/>
<location line="+57"/>
<source>To</source>
<translation>À</translation>
</message>
<message>
<location line="-96"/>
<location line="+2"/>
<location line="+18"/>
<location line="+2"/>
<source>own address</source>
<translation>votre propre adresse</translation>
</message>
<message>
<location line="-22"/>
<location line="+20"/>
<source>label</source>
<translation>étiquette</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+44"/>
<location line="+20"/>
<location line="+40"/>
<source>Credit</source>
<translation>Crédit</translation>
</message>
<message numerus="yes">
<location line="-114"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>arrive à maturité dans %n bloc de plus</numerusform><numerusform>arrive à maturité dans %n blocks supplémentaires</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>refusé</translation>
</message>
<message>
<location line="+43"/>
<location line="+8"/>
<location line="+16"/>
<location line="+42"/>
<source>Debit</source>
<translation>Débit</translation>
</message>
<message>
<location line="-52"/>
<source>Transaction fee</source>
<translation>Frais de transaction</translation>
</message>
<message>
<location line="+19"/>
<source>Net amount</source>
<translation>Montant net</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Commentaire</translation>
</message>
<message>
<location line="+12"/>
<source>Transaction ID</source>
<translation>ID de la transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informations de débogage</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Entrants</translation>
</message>
<message>
<location line="+44"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>vrai</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>faux</translation>
</message>
<message>
<location line="-266"/>
<source>, has not been successfully broadcast yet</source>
<translation>, n’a pas encore été diffusée avec succès</translation>
</message>
<message>
<location line="+36"/>
<location line="+20"/>
<source>unknown</source>
<translation>inconnu</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Détails de la transaction</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ce panneau affiche une description détaillée de la transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+217"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+54"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmée (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation>
</message>
<message>
<location line="-51"/>
<source>Narration</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>Offline</source>
<translation>Hors ligne</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Non confirmé</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirmation (%1 sur %2 confirmations recommandées)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>En conflit</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 confirmations, sera disponible après %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ce bloc n’a été reçu par aucun autre nœud et ne sera probablement pas accepté !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Généré mais pas accepté</translation>
</message>
<message>
<location line="+49"/>
<source>(n/a)</source>
<translation>(n.d)</translation>
</message>
<message>
<location line="+202"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>État de la transaction. Laissez le pointeur de la souris sur ce champ pour voir le nombre de confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date et heure de réception de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type de transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>L’adresse de destination de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Montant ajouté ou enlevé au solde.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+393"/>
<location line="+246"/>
<source>Sending...</source>
<translation>Envoi...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>People version</source>
<translation>Version People</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Utilisation :</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or peopled</source>
<translation>Envoyer commande à -server ou peopled</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Lister les commandes</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Obtenir de l’aide pour une commande</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Options :</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: people.conf)</source>
<translation>Spécifier le fichier de configuration (defaut: people.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: peopled.pid)</source>
<translation>Spécifier le fichier pid (defaut: peopled.pid)
</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Spécifiez le fichier de portefeuille (dans le répertoire de données)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Spécifier le répertoire de données</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 51737 or testnet: 51997)</source>
<translation>Écouter les connexions sur le <port> (default: 51737 or testnet: 51997)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Garder au plus <n> connexions avec les pairs (par défaut : 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Se connecter à un nœud pour obtenir des adresses de pairs puis se déconnecter</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Spécifier votre propre adresse publique</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Connexion à l'adresse fournie. Utiliser la notation [machine]:port pour les adresses IPv6</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation>Stacker vos monnaies afin de soutenir le réseau et d'obtenir des intérêts (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Seuil de déconnexion des pairs de mauvaise qualité (par défaut : 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Délai en secondes de refus de reconnexion aux pairs de mauvaise qualité (par défaut : 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Une erreur est survenue lors du réglage du port RPC %u pour écouter sur IPv4 : %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Détacher la base de donnée des blocks et adresses. Augmente le temps de fermeture (default: 0)</translation>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Erreur: La transaction a été rejetée. Cela peut se produire si une quantité d'argent de votre portefeuille a déjà été dépensée, comme dans le cas où une copie du fichier wallet.dat aurait été utilisée afin d'effectuer des dépenses, à la place du fichier courant.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Erreur: Cette transaction requière des frais minimum de %s a cause de son montant, de sa complexité ou de l'utilisation de fonds récemment reçus.</translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 51736 or testnet: 51996)</source>
<translation>Écouter les connexions JSON-RPC sur le <port> (default: 51736 or testnet: 51996)</translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter les commandes de JSON-RPC et de la ligne de commande</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Erreur: La création de cette transaction à échouée</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Erreur: Portefeuille verrouillé, impossible d'effectuer cette transaction</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Importation du fichier blockchain</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Importation du fichier blockchain</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Fonctionner en arrière-plan en tant que démon et accepter les commandes</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utiliser le réseau de test</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepter les connexions entrantes (par défaut : 1 si aucun -proxy ou -connect )</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Une erreur est survenue lors du réglage du port RPC %u pour écouter sur IPv6, retour à IPv4 : %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Erreur lors de l'initialisation de l'environnement de base de données %s! Afin de procéder à la récupération, une SAUVEGARDE DE CE REPERTOIRE est nécessaire, puis, supprimez le contenu entier de ce répertoire, à l'exception du fichier wallet.dat </translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Fixer la taille maximale d'un block en bytes (default: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Attention : -paytxfee est réglée sur un montant très élevé ! Il s'agit des frais de transaction que vous payerez si vous envoyez une transaction.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong People will not work properly.</source>
<translation>Avertissement: Veuillez vérifier la date et l'heure de votre ordinateur. People ne pourra pas fonctionner correctement si l'horloge est réglée de façon incorrecte</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Avertissement : une erreur est survenue lors de la lecture de wallet.dat ! Toutes les clefs ont été lues correctement mais les données de transaction ou les entrées du carnet d'adresses sont peut-être incorrectes ou manquantes.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Avertissement : wallet.dat corrompu, données récupérées ! Le fichier wallet.dat original a été enregistré en tant que wallet.{timestamp}.bak dans %s ; si votre solde ou transactions sont incorrects vous devriez effectuer une restauration depuis une sauvegarde.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tenter de récupérer les clefs privées d'un wallet.dat corrompu</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Options de création de bloc :</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Ne se connecter qu'au(x) nœud(s) spécifié(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Découvrir sa propre adresse IP (par défaut : 1 lors de l'écoute et si aucun -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Échec de l'écoute sur un port quelconque. Utilisez -listen=0 si vous voulez ceci.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Trouvez des peers utilisant DNS lookup (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Politique de synchronisation des checkpoints (default: strict)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>Adresse -tor invalide: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Montant incorrect pour -reservebalance=<montant></translation>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Tampon maximal de réception par « -connection » <n>*1 000 octets (par défaut : 5 000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Tampon maximal d'envoi par « -connection », <n>*1 000 octets (par défaut : 1 000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Se connecter uniquement aux nœuds du réseau <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Voir les autres informations de débogage. Implique toutes les autres options -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Voir les autres informations de débogage du réseau</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Horodater les messages de debug</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Options SSL : (voir le Wiki de Bitcoin pour les instructions de configuration du SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Sélectionner la version du proxy socks à utiliser (4-5, par défaut: 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Fixer la taille maximale d'un block en bytes (default: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Définir la taille minimale de bloc en octets (par défaut : 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Réduire le fichier debug.log lors du démarrage du client (par défaut : 1 lorsque -debug n'est pas présent)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Spécifier le délai d'expiration de la connexion en millisecondes (par défaut : 5 000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>Impossible de "signer" le checkpoint, mauvaise clef de checkpoint?
</translation>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 1 lors de l'écoute)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utiliser un proxy pour atteindre les services cachés (défaut: équivalent à -proxy)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nom d'utilisateur pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Vérification d'intégrité de la base de données...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>ATTENTION : violation du checkpoint de synchronisation, mais ignorée!</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Avertissement: Espace disque faible!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Avertissement : cette version est obsolète, une mise à niveau est nécessaire !</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrompu, la récupération a échoué</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Mot de passe pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=peoplerpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "People Alert" [email protected]
</source>
<translation>%s, vous devez définir un mot de passe rpc 'rpcpassword' au sein du fichier de configuration:
%s
Il est recommandé d'utiliser le mot de passe aléatoire suivant:
rpcuser=peoplerpc
rpcpassword=%s
(il n'est pas nécessaire de retenir ce mot de passe)
Le nom d'utilisateur et le mot de passe doivent IMPERATIVEMENT être différents.
Si le fichier n'existe pas, il est nécessaire de le créer, avec les droit de lecture au propriétaire seulement.
Il est également recommandé d'utiliser l'option alertnotify afin d'être notifié des problèmes;
par exemple: alertnotify=echo %%s | mail -s "Alerte People" [email protected]
</translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Find peers using internet relay chat (default: 1) {0)?}</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Synchronisation de l'horloge avec d'autres noeuds. Désactiver si votre serveur est déjà synchronisé avec le protocole NTP (défaut: 1)</translation>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Lors de la création de transactions, ignore les entrées dont la valeur sont inférieures (défaut: 0.01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Autoriser les connexions JSON-RPC depuis l'adresse IP spécifiée</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envoyer des commandes au nœud fonctionnant sur <ip> (par défaut : 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Exécuter la commande lorsque le meilleur bloc change (%s dans cmd est remplacé par le hachage du bloc)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Exécuter la commande lorsqu'une transaction de portefeuille change (%s dans la commande est remplacée par TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Nécessite a confirmations pour modification (défaut: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation>Force les scripts de transaction à utiliser des opérateurs PUSH canoniques (défaut: 1)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Exécute une commande lorsqu'une alerte correspondante est reçue (%s dans la commande est remplacé par message)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Mettre à niveau le portefeuille vers le format le plus récent</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Régler la taille de la réserve de clefs sur <n> (par défaut : 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Réanalyser la chaîne de blocs pour les transactions de portefeuille manquantes</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Nombre de blocs à vérifier loes du démarrage (défaut: 2500, 0 = tous)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Niveau d'approfondissement de la vérification des blocs (0-6, default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importe les blocs d'un fichier externe blk000?.dat</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Utiliser OpenSSL (https) pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Fichier de certificat serveur (par défaut : server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clef privée du serveur (par défaut : server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Algorithmes de chiffrements acceptés (défaut: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Erreur: Portefeuille déverrouillé uniquement pour "stacking" , impossible d'effectuer cette transaction</translation>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>AVERTISSEMENT: point de contrôle invalide! Les transactions affichées peuvent être incorrectes! Il est peut-être nécessaire d'effectuer une mise à jour, ou d'avertir les développeurs du projet.</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Ce message d'aide</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Le portefeuille %s réside en dehors répertoire de données %s</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. People is probably already running.</source>
<translation>Echec lors de la tentative de verrouillage des données du répertoire %s. L'application People est probablement déjà en cours d'exécution</translation>
</message>
<message>
<location line="-98"/>
<source>People</source>
<translation>People</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Impossible de se lier à %s sur cet ordinateur (bind a retourné l'erreur %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Se connecter à travers un proxy socks</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Autoriser les recherches DNS pour -addnode, -seednode et -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Chargement des adresses…</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Erreur de chargement du fichier blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erreur lors du chargement de wallet.dat : portefeuille corrompu</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of People</source>
<translation>Erreur de chargement du fichier wallet.dat: le portefeuille nécessite une version plus récente de l'application People</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart People to complete</source>
<translation>le portefeuille nécessite d'être réédité : Merci de relancer l'application People</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erreur lors du chargement de wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresse -proxy invalide : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Réseau inconnu spécifié sur -onlynet : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Version inconnue de serveur mandataire -socks demandée : %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Impossible de résoudre l'adresse -bind : « %s »</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Impossible de résoudre l'adresse -externalip : « %s »</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Montant invalide pour -paytxfee=<montant> : « %s »</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Erreur: Impossible de démarrer le noeud</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Envoi...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Montant invalide</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fonds insuffisants</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Chargement de l’index des blocs…</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Ajouter un nœud auquel se connecter et tenter de garder la connexion ouverte</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. People is probably already running.</source>
<translation>Connexion au port %s impossible. L'application People est probablement déjà en cours d'exécution</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Frais par KB à ajouter à vos transactions sortantes</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Montant invalide pour -mininput=<amount>: '%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Chargement du portefeuille…</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Impossible de revenir à une version inférieure du portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Impossible d'initialiser la "keypool"</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossible d'écrire l'adresse par défaut</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Nouvelle analyse…</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Chargement terminé</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Pour utiliser l'option %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Vous devez ajouter la ligne rpcpassword=<mot-de-passe> au fichier de configuration :
%s
Si le fichier n'existe pas, créez-le avec les droits de lecture seule accordés au propriétaire.</translation>
</message>
</context>
</TS><|fim▁end|> | <source>You need the Wallet Recovery Phrase to restore this wallet. Write it down and keep them somewhere safe.
You will be asked to confirm the Wallet Recovery Phrase in the next screen to ensure you have written it down correctly</source> |
<|file_name|>workitem-detailpage.ts<|end_file_name|><|fim▁begin|>import * as ui from '../../ui';
import { WorkItemQuickPreview } from './workitem-quickpreview';<|fim▁hole|>
}<|fim▁end|> |
export class WorkItemDetailPage extends WorkItemQuickPreview {
detailPageDiv = new ui.BaseElement(this.$('#wi-detail-form'), 'wi detail page'); |
<|file_name|>disk_manager.go<|end_file_name|><|fim▁begin|>/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fc
import (
"os"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
)
// Abstract interface to disk operations.
type diskManager interface {
MakeGlobalPDName(disk fcDisk) string
MakeGlobalVDPDName(disk fcDisk) string
// Attaches the disk to the kubelet's host machine.
AttachDisk(b fcDiskMounter) (string, error)
// Detaches the disk from the kubelet's host machine.
DetachDisk(disk fcDiskUnmounter, devicePath string) error
// Detaches the block disk from the kubelet's host machine.
DetachBlockFCDisk(disk fcDiskUnmapper, mntPath, devicePath string) error
}
// utility to mount a disk based filesystem
func diskSetUp(manager diskManager, b fcDiskMounter, volPath string, mounter mount.Interface, fsGroup *int64) error {
globalPDPath := manager.MakeGlobalPDName(*b.fcDisk)
noMnt, err := mounter.IsLikelyNotMountPoint(volPath)
if err != nil && !os.IsNotExist(err) {
glog.Errorf("cannot validate mountpoint: %s", volPath)
return err
}
if !noMnt {
return nil
}
if err := os.MkdirAll(volPath, 0750); err != nil {
glog.Errorf("failed to mkdir:%s", volPath)
return err
}
// Perform a bind mount to the full path to allow duplicate mounts of the same disk.
options := []string{"bind"}
if b.readOnly {
options = append(options, "ro")
}
err = mounter.Mount(globalPDPath, volPath, "", options)
if err != nil {
glog.Errorf("Failed to bind mount: source:%s, target:%s, err:%v", globalPDPath, volPath, err)
noMnt, mntErr := b.mounter.IsLikelyNotMountPoint(volPath)
if mntErr != nil {
glog.Errorf("IsLikelyNotMountPoint check failed: %v", mntErr)
return err
}
if !noMnt {
if mntErr = b.mounter.Unmount(volPath); mntErr != nil {
glog.Errorf("Failed to unmount: %v", mntErr)
return err
}<|fim▁hole|> }
if !noMnt {
// will most likely retry on next sync loop.
glog.Errorf("%s is still mounted, despite call to unmount(). Will try again next sync loop.", volPath)
return err
}
}
os.Remove(volPath)
return err
}
if !b.readOnly {
volume.SetVolumeOwnership(&b, fsGroup)
}
return nil
}<|fim▁end|> | noMnt, mntErr = b.mounter.IsLikelyNotMountPoint(volPath)
if mntErr != nil {
glog.Errorf("IsLikelyNotMountPoint check failed: %v", mntErr)
return err |
<|file_name|>classification-svc-iris.py<|end_file_name|><|fim▁begin|>import numpy as np
from sklearn import datasets, svm
<|fim▁hole|>iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
# Set aside the first 10 data points as test data
indicies = np.random.permutation(len(iris_X))
iris_X_train = iris_X[indicies[:-10]]
iris_y_train = iris_y[indicies[:-10]]
iris_X_test = iris_X[indicies[-10:]]
iris_y_test = iris_y[indicies[-10:]]
svc = svm.SVC(kernel='linear')
print(svc.fit(iris_X_train, iris_y_train))<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO Ematelot SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant la commande 'matelot' et ses sous-commandes.
Dans ce fichier se trouve la commande même.
"""
from primaires.interpreteur.commande.commande import Commande
from .affecter import PrmAffecter
from .creer import PrmCreer
from .editer import PrmEditer
from .info import PrmInfo
from .liste import PrmListe
from .poste import PrmPoste
from .promouvoir import PrmPromouvoir
from .recruter import PrmRecruter
from .renommer import PrmRenommer
from .retirer import PrmRetirer
from .score import PrmScore
class CmdMatelot(Commande):
"""Commande 'matelot'.
"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "matelot", "seaman")
self.nom_categorie = "navire"
self.aide_courte = "manipulation des matelots"
self.aide_longue = \
"Cette commande permet de manipuler les matelots de " \
"votre équipage individuellement. Il existe également " \
"la commande %équipage% qui permet de manipuler l'équipage " \
"d'un coup d'un seul."
def ajouter_parametres(self):
"""Ajout des paramètres"""<|fim▁hole|> self.ajouter_parametre(PrmAffecter())
self.ajouter_parametre(PrmCreer())
self.ajouter_parametre(PrmEditer())
self.ajouter_parametre(PrmInfo())
self.ajouter_parametre(PrmListe())
self.ajouter_parametre(PrmPoste())
self.ajouter_parametre(PrmPromouvoir())
self.ajouter_parametre(PrmRecruter())
self.ajouter_parametre(PrmRenommer())
self.ajouter_parametre(PrmRetirer())
self.ajouter_parametre(PrmScore())<|fim▁end|> | |
<|file_name|>closure.rs<|end_file_name|><|fim▁begin|>fn main(){
let is_even = |x| {
x%2==0<|fim▁hole|> println!("{} is even ? {}",no,is_even(no));
}<|fim▁end|> | };
let no = 13; |
<|file_name|>Exercise 3.py<|end_file_name|><|fim▁begin|># Exercise 3
# creating a simple loop<|fim▁hole|>
#set the start value
i = 0
upper_range=10
for i in range(upper_range):
print(str(i+1)+ " this is a loop")<|fim▁end|> | # print out 1 thru 10 |
<|file_name|>mut_ref.rs<|end_file_name|><|fim▁begin|>// Compiler:
//
// Run-time:
// stdout: 2
// 7
// 6
// 11
#![allow(unused_attributes)]
#![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)]
#![no_std]
#![no_core]
/*
* Core
*/
// Because we don't have core yet.
#[lang = "sized"]
pub trait Sized {}
#[lang = "copy"]
trait Copy {
}
impl Copy for isize {}
impl Copy for *mut i32 {}
impl Copy for usize {}
impl Copy for u8 {}
impl Copy for i8 {}
impl Copy for i32 {}
#[lang = "receiver"]
trait Receiver {
}
#[lang = "freeze"]
pub(crate) unsafe auto trait Freeze {}
#[lang = "panic_location"]
struct PanicLocation {
file: &'static str,
line: u32,
column: u32,
}
mod libc {
#[link(name = "c")]
extern "C" {
pub fn puts(s: *const u8) -> i32;
pub fn fflush(stream: *mut i32) -> i32;
pub fn printf(format: *const i8, ...) -> i32;
pub static STDOUT: *mut i32;
}
}
mod intrinsics {
extern "rust-intrinsic" {
pub fn abort() -> !;
}
}
#[lang = "panic"]
#[track_caller]
#[no_mangle]
pub fn panic(_msg: &str) -> ! {
unsafe {
libc::puts("Panicking\0" as *const str as *const u8);
libc::fflush(libc::STDOUT);
intrinsics::abort();
}
}
#[lang = "add"]
trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
impl Add for u8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i8 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for i32 {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for usize {
type Output = Self;
fn add(self, rhs: Self) -> Self {
self + rhs
}
}
impl Add for isize {
type Output = Self;<|fim▁hole|> }
}
/*
* Code
*/
struct Test {
field: isize,
}
fn test(num: isize) -> Test {
Test {
field: num + 1,
}
}
fn update_num(num: &mut isize) {
*num = *num + 5;
}
#[start]
fn main(mut argc: isize, _argv: *const *const u8) -> isize {
let mut test = test(argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut test.field);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field);
}
update_num(&mut argc);
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
let refe = &mut argc;
*refe = *refe + 5;
unsafe {
libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc);
}
0
}<|fim▁end|> |
fn add(self, rhs: Self) -> Self {
self + rhs |
<|file_name|>SSFP.py<|end_file_name|><|fim▁begin|>from mdt import CompartmentTemplate
from mdt.lib.post_processing import DTIMeasures
__author__ = 'Robbert Harms'
__date__ = '2017-08-03'
__maintainer__ = 'Robbert Harms'
__email__ = '[email protected]'
__licence__ = 'LGPL v3'
class SSFP_Ball(CompartmentTemplate):
parameters = ('d', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2')
dependencies = ('SSFP',)
cl_code = '''
return SSFP(d, delta, G, TR, flip_angle, b1, T1, T2);
'''
class SSFP_Stick(CompartmentTemplate):
parameters = ('g', 'd', 'theta', 'phi', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2')<|fim▁hole|> dependencies = ('SSFP',)
cl_code = '''
double adc = d * pown(dot(g, (float4)(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta), 0.0)), 2);
return SSFP(adc, delta, G, TR, flip_angle, b1, T1, T2);
'''
class SSFP_Tensor(CompartmentTemplate):
parameters = ('g', 'd', 'dperp0', 'dperp1', 'theta', 'phi', 'psi', 'delta',
'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2')
dependencies = ('SSFP', 'TensorApparentDiffusion')
cl_code = '''
double adc = TensorApparentDiffusion(theta, phi, psi, d, dperp0, dperp1, g);
return SSFP(adc, delta, G, TR, flip_angle, b1, T1, T2);
'''
constraints = '''
constraints[0] = dperp0 - d;
constraints[1] = dperp1 - dperp0;
'''
prior = 'return dperp1 < dperp0 && dperp0 < d;'
extra_optimization_maps = [DTIMeasures.extra_optimization_maps]
extra_sampling_maps = [DTIMeasures.extra_sampling_maps]
class SSFP_Zeppelin(CompartmentTemplate):
parameters = ('g', 'd', 'dperp0', 'theta', 'phi', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2')
dependencies = ('SSFP',)
cl_code = '''
double adc = dperp0 + ((d - dperp0) * pown(dot(g, (float4)(cos(phi) * sin(theta),
sin(phi) * sin(theta), cos(theta), 0.0)), 2);
return SSFP(adc, delta, G, TR, flip_angle, b1, T1, T2);
'''<|fim▁end|> | |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>import importlib.util
import logging
import os
import warnings
from os import getenv
from typing import Any, Optional, Mapping, ClassVar
log = logging.getLogger(__name__)
default_settings_dict = {
'connect_timeout_seconds': 15,
'read_timeout_seconds': 30,
'max_retry_attempts': 3,
'base_backoff_ms': 25,
'region': None,
'max_pool_connections': 10,
'extra_headers': None,
}
OVERRIDE_SETTINGS_PATH = getenv('PYNAMODB_CONFIG', '/etc/pynamodb/global_default_settings.py')
def _load_module(name, path):
# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec) # type: ignore
spec.loader.exec_module(module) # type: ignore
return module
override_settings = {}<|fim▁hole|>if os.path.isfile(OVERRIDE_SETTINGS_PATH):
override_settings = _load_module('__pynamodb_override_settings__', OVERRIDE_SETTINGS_PATH)
if hasattr(override_settings, 'session_cls') or hasattr(override_settings, 'request_timeout_seconds'):
warnings.warn("The `session_cls` and `request_timeout_second` options are no longer supported")
log.info('Override settings for pynamo available {}'.format(OVERRIDE_SETTINGS_PATH))
else:
log.info('Override settings for pynamo not available {}'.format(OVERRIDE_SETTINGS_PATH))
log.info('Using Default settings value')
def get_settings_value(key: str) -> Any:
"""
Fetches the value from the override file.
If the value is not present, then tries to fetch the values from constants.py
"""
if hasattr(override_settings, key):
return getattr(override_settings, key)
if key in default_settings_dict:
return default_settings_dict[key]
return None
class OperationSettings:
"""
Settings applicable to an individual operation.
When set, the settings in this object supersede the global and model settings.
"""
default: ClassVar['OperationSettings']
def __init__(self, *, extra_headers: Optional[Mapping[str, Optional[str]]] = None) -> None:
"""
Initializes operation settings.
:param extra_headers: if set, extra headers to add to the HTTP request. The headers are merged
on top of extra headers derived from settings or models' Meta classes. To delete a header, set its value
to `None`.
"""
self.extra_headers = extra_headers
OperationSettings.default = OperationSettings()<|fim▁end|> | |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013 Alon Swartz <[email protected]>
#
# This file is part of OctoHub.
#
# OctoHub is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
import simplejson as json
class ResponseError(Exception):
"""Accessible attributes: error
error (AttrDict): Parsed error response
"""
def __init__(self, error):
Exception.__init__(self, error)
self.error = error
def __str__(self):
return json.dumps(self.error, indent=1)
class OctoHubError(Exception):<|fim▁hole|><|fim▁end|> | pass |
<|file_name|>exp_entries.py<|end_file_name|><|fim▁begin|># coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines Entry classes for containing experimental data.
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "[email protected]"
__date__ = "Jun 27, 2012"
from pymatgen.analysis.phase_diagram import PDEntry
from pymatgen.core.composition import Composition
from monty.json import MSONable
from pymatgen.analysis.thermochemistry import ThermoData
class ExpEntry(PDEntry, MSONable):
"""
An lightweight ExpEntry object containing experimental data for a
composition for many purposes. Extends a PDEntry so that it can be used for
phase diagram generation and reaction calculation.
Current version works only with solid phases and at 298K. Further
extensions for temperature dependence are planned.
"""
def __init__(self, composition, thermodata, temperature=298):
"""
Args:
composition: Composition of the entry. For flexibility, this can take
the form of all the typical input taken by a Composition, including
a {symbol: amt} dict, a string formula, and others.
thermodata: A sequence of ThermoData associated with the entry.
temperature: A temperature for the entry in Kelvin. Defaults to 298K.
"""
comp = Composition(composition)
self._thermodata = thermodata
found = False
enthalpy = float("inf")
for data in self._thermodata:
if data.type == "fH" and data.value < enthalpy and \
(data.phaseinfo != "gas" and data.phaseinfo != "liquid"):
enthalpy = data.value
found = True
if not found:<|fim▁hole|> "values.")
self.temperature = temperature
super().__init__(comp, enthalpy)
def __repr__(self):
return "ExpEntry {}, Energy = {:.4f}".format(self.composition.formula,
self.energy)
def __str__(self):
return self.__repr__()
@classmethod
def from_dict(cls, d):
"""
:param d: Dict representation.
:return: ExpEntry
"""
thermodata = [ThermoData.from_dict(td) for td in d["thermodata"]]
return cls(d["composition"], thermodata, d["temperature"])
def as_dict(self):
"""
:return: MSONable dict
"""
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"thermodata": [td.as_dict() for td in self._thermodata],
"composition": self.composition.as_dict(),
"temperature": self.temperature}<|fim▁end|> | raise ValueError("List of Thermodata does not contain enthalpy " |
<|file_name|>default.js<|end_file_name|><|fim▁begin|>/*
* Lupus in Tabula
* ...un progetto di Edoardo Morassutto
* Contributors:
* - 2014 Edoardo Morassutto <[email protected]>
*/
var path = "";
var APIdir = path + "/api";
var errorCount = 0;
var lastError = 0;
var lastNotificationUpdate = null;
function logout() {
$.ajax({
url: APIdir+"/logout",
type: "GET",
dataType: "json",
async: false,
success: function() {
window.location.href = path + "/login";
},
error: function(e) {
window.location.href = path + "/login";
}
});
}
function isShortName(name) {
var regex = /^[a-zA-Z][a-zA-Z0-9]{0,9}$/;
return regex.test(name);
}
function isValidDescr(descr) {
var regex = /^[a-zA-Z0-9][a-zA-Z0-9 ]{0,43}[a-zA-Z0-9]$/;
return regex.test(descr);
}
function showError(message) {
var div = $("<div>")
.addClass("alert")
.addClass("alert-danger")
.addClass("alert-dismissable")
.attr("id", "error-"+(errorCount++));
div.append('<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>');
div.append(message.error);
$("nav.navbar").after(div);
setTimeout(removeError, 2000);
}
function getErrorMessage(jqError) {
try {
return JSON.parse(jqError.responseText);
} catch (e) {
return JSON.stringify(jqError);
}
}
function removeError() {
$("#error-"+(lastError++)).fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}
<|fim▁hole|>function removeNotification() {
var $this = $(this);
var id_notification = $this.attr('data-id-notification');
$.ajax({
url: APIdir + "/notification/dismiss",
data: { id_notification: id_notification },
dataType: 'json',
type: 'POST',
success: function(data) {
$this.closest('.notification-element').remove();
if ($('.notification-element').length == 0)
$('.dropdown-menu').append("<p id='notifications-empty'>Nessuna notifica recente...</p>");
},
error: function(error) {
console.error(error);
showError(getErrorMessage(error));
}
});
return false;
}
function refreshNotifications() {
$.ajax({
url: APIdir + "/notification/update",
data: { since: lastNotificationUpdate },
dataType: 'json',
type: 'GET',
success: function (data) {
lastNotificationUpdate = new Date();
appendNotifications(data);
},
error: function (error) {
console.error(error);
showError(getErrorMessage(error));
}
});
return false;
}
function appendNotifications(list) {
if (list.length == 0) return;
var $notifications = $("#notifications .dropdown-menu");
$("#notifications-empty").remove();
while (list.length) {
var noti = list.pop();
var $noti = $("<a href='"+noti.link+"' class='notification-element'>");
$noti.append(
$('<div class="btn-dismiss-notification" data-id-notification="'+noti.id_notification+'">')
.append('<div class="glyphicon glyphicon-remove"></div>')
.click(removeNotification)
);
$noti.append(noti.message);
$noti.insertAfter("#notifications-title");
}
}
$(function() {
if (location.pathname != path + "/login") {
$(".btn-dismiss-notification").click(removeNotification);
$("#notifications-refresh").click(refreshNotifications);
$("#notifications-toggle").dropdown();
$("#notifications").on("show.bs.dropdown", function () {
refreshNotifications();
});
refreshNotifications();
}
});<|fim▁end|> | |
<|file_name|>pendingChain.go<|end_file_name|><|fim▁begin|>package internal<|fim▁hole|>
import G "github.com/ionous/sashimi/game"
// PendingChain implements runtime.IChain, it fills out the chained callback if the user links one in.
type PendingChain struct {
//node **ChainedCallback
src *GameEventAdapter
}
func NewPendingChain(src *GameEventAdapter, _ Future) PendingChain {
//return PendingChain{src, future.GetChain()}
return PendingChain{src}
}
func (c PendingChain) Then(cb G.Callback) {
// watch for null objects
if c.src != nil {
// if c.node != nil {
// *(c.node) = &ChainedCallback{c.data, cb}
// }
chain := ChainedCallback{c.src.data, cb}
chain.Run(c.src.Game)
}
}<|fim▁end|> | |
<|file_name|>errors.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (C) 2008 Osmo Salomaa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__all__ = ("AffirmationError",)
class AffirmationError(Exception):
"""<|fim▁hole|> :exc:`AffirmationError` is like :exc:`AssertionError`, but without
the special reliance on :const:`__debug__` and given optimization options.
:exc:`AffirmationError` can be used to provide essential checks of boolean
values instead of optional debug checks.
"""
pass<|fim▁end|> | Something expected to be ``True`` was ``False``.
|
<|file_name|>sysvinit.rs<|end_file_name|><|fim▁begin|>use std::result::Result;
use backend::Backend;
use backend::command::Command;
use provider::error::Error;
use provider::Output;
use provider::service::shell::ShellProvider;
#[derive(Clone, Debug)]
pub struct SysVInit;
impl ShellProvider for SysVInit {
fn is_running(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("service {} status", name));
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn is_enabled(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let mut c = Command::new(&format!("chkconfig --list {}", name));
c.pipe("grep 3:on");
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn disable(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("chkconfig {} off", name));
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn enable(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("chkconfig {} on", name));<|fim▁hole|> let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn start(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("service {} start", name));
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn stop(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("service {} stop", name));
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn reload(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("service {} reload", name));
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn restart(&self, name: &str, b: &Backend) -> Result<Output, Error> {
let c = Command::new(&format!("service {} restart", name));
let success = match b.run_command(c) {
Ok(r) => r.success,
Err(_) => false,
};
Ok(Output::Bool(success))
}
fn box_clone(&self) -> Box<ShellProvider> {
Box::new((*self).clone())
}
}<|fim▁end|> | |
<|file_name|>ClientSignaler.ts<|end_file_name|><|fim▁begin|>import * as SimplePeer from "simple-peer";
import { IState } from "../redux/State";
import { AbstractSignaler, IOfferMessage, IResponseMessage } from "./AbstractSignaler";
interface IResponseStore {
id: string;
signalData: SimplePeer.SignalData;
}<|fim▁hole|>export class ClientSignaler extends AbstractSignaler {
private deliverSignal: (signalData: SimplePeer.SignalData) => void;
// NOTE: If these object get any more complicated, add to store
private responseData: IResponseStore[];
private offerData: SimplePeer.SignalData[];
constructor() {
super();
this.offerData = [];
this.responseData = [];
this.socket.on("response", this.dealWithResponse);
}
public onResponse(deliverSignal: (signalData: SimplePeer.SignalData) => void) {
this.deliverSignal = deliverSignal;
for (const data of this.responseData) {
if (this.getID() === data.id) {
deliverSignal(data);
}
}
this.responseData = [];
}
public sendSignal = (signalData: SimplePeer.SignalData) => {
if (!this.getServerStatus()) {
this.offerData.push(signalData);
}
else {
this.sendOffer(this.formOffer(signalData));
}
}
protected notify(oldState: IState, nextState: IState) {
if (nextState.commonPeerState.serverStatus && this.offerData.length > 0) {
for (const signalData of this.offerData) {
this.sendOffer(this.formOffer(signalData));
}
this.offerData = [];
}
}
private sendOffer = (offerMessage: IOfferMessage) => {
this.socket.emit("offer", offerMessage);
}
private formOffer = (data: SimplePeer.SignalData): IOfferMessage => {
return {
clientID: this.getID(),
hostID: this.getClientState().hostID,
signalData: data,
};
}
private dealWithResponse = (responseMessage: IResponseMessage) => {
if (responseMessage.clientID === this.getID()) {
if (this.deliverSignal) {
this.deliverSignal(responseMessage.signalData);
}
else {
this.responseData.push({
id: responseMessage.clientID,
signalData: responseMessage.signalData,
});
}
}
}
}<|fim▁end|> | |
<|file_name|>FeatureIterator.cpp<|end_file_name|><|fim▁begin|>#include "FeatureIterator.h"
#include "Random.h"
#include <functional>
namespace dungeon
{
////////////////////////////////////////////////////////////////////////////////
// ADJUSTERS
////////////////////////////////////////////////////////////////////////////////
AForward::AForward(const Feature& feature) :
mStart(randomRange(0,feature.height() - 1)),
mOffset(feature.offset(mStart))
{
}
AMirror::AMirror(const Feature& feature) :
mStart(randomRange(0,feature.height() - 1)),
mOffset(feature.offset(feature.height() - 1 - mStart))
{
}
ATranspose::ATranspose(const Feature& feature) :
mStart(randomRange(0,feature.width(0) - 1)),
mOffset(-mStart - feature.offset(0))
{
}
AMirrorTranspose::AMirrorTranspose(const Feature& feature) :
mStart(randomRange(0,feature.width(feature.height() - 1) - 1)),
mOffset(-mStart - feature.offset(feature.height() - 1))
{
}
////////////////////////////////////////////////////////////////////////////////
// ITERATORS
////////////////////////////////////////////////////////////////////////////////
IForward::IForward(int height) :
mHeight(height),
mCurrent(0)
{
}
int IForward::begin() const
{
mCurrent = 0;
return mCurrent;
}<|fim▁hole|> return mCurrent;
}
int IForward::end() const
{
return mHeight;
}
IBackward::IBackward(int height) :
mHeight(height),
mCurrent(0)
{
}
int IBackward::begin() const
{
mCurrent = mHeight - 1;
return mCurrent;
}
int IBackward::next()
{
--mCurrent;
return mCurrent;
}
int IBackward::end() const
{
return -1;
}
}<|fim▁end|> |
int IForward::next()
{
++mCurrent; |
<|file_name|>tumble.go<|end_file_name|><|fim▁begin|>package demo
import (
_ "fmt"
cp "github.com/eka-tel72/go-chipmunk62/chipmunk"
)
/*
#include <stdlib.h>
int Random(void)
{
return rand();
}
void Seed(unsigned int i)
{
srand(i);
}
*/
import "C"
type tumble struct {
*demoClass
rogueBoxBody *cp.Body
}
var tumbleInst = &tumble{
&demoClass{
name: "Tumble",
timestep: 1.0/180.0,
},
nil,
}
func (t *tumble) Update(space *cp.Space, dt float64) {
fdt := cp.Float(dt)
cp.BodyUpdatePosition(t.rogueBoxBody, fdt)
cp.SpaceStep(space, fdt)
}
func tumbleAddBox(space *cp.Space, pos cp.Vect, mass, width, height cp.Float) {
body := cp.SpaceAddBody( space, cp.BodyNew(mass, cp.MomentForBox(mass, width, height)) )
cp.BodySetPos(body, pos)
shape := cp.SpaceAddShape(space, cp.BoxShapeNew(body, width, height))
cp.ShapeSetElasticity(shape, 0.0)
cp.ShapeSetFriction(shape, 0.7)
}
func tumbleAddSegment(space *cp.Space, pos cp.Vect, mass, width, height cp.Float) {
body := cp.SpaceAddBody( space, cp.BodyNew(mass, cp.MomentForBox(mass, width, height)) )
cp.BodySetPos(body, pos)
shape := cp.SpaceAddShape(space, cp.SegmentShapeNew(body, cp.V(0.0, (height - width)/2.0), cp.V(0.0, (width - height)/2.0), width/2.0))
cp.ShapeSetElasticity(shape, 0.0)
cp.ShapeSetFriction(shape, 0.7)
}
func tumbleAddCircle(space *cp.Space, pos cp.Vect, mass, radius cp.Float) {
body := cp.SpaceAddBody( space, cp.BodyNew(mass, cp.MomentForCircle(mass, 0.0, radius, cpvzero)) )
cp.BodySetPos(body, pos)
shape := cp.SpaceAddShape(space, cp.CircleShapeNew(body, radius, cpvzero))
cp.ShapeSetElasticity(shape, 0.0)
cp.ShapeSetFriction(shape, 0.7)
}
func (t *tumble) Init() *cp.Space {
C.Seed(45073)
space := cp.SpaceNew()
cp.SpaceSetGravity(space, cp.V(0, -600))
rogueBoxBody := cp.BodyNew(infinity, infinity)
cp.BodySetAngVel(rogueBoxBody, 0.4)
a := cp.V(-200, -200)<|fim▁hole|> c := cp.V( 200, 200)
d := cp.V( 200, -200)
seg := [][]cp.Vect {{a, b}, {b, c}, {c, d}, {d, a}}
for i := 0; i < len(seg); i++ {
vs := seg[i]
shape := cp.SpaceAddShape(space, cp.SegmentShapeNew(rogueBoxBody, vs[0], vs[1], 0.0))
cp.ShapeSetElasticity(shape, 1.0)
cp.ShapeSetFriction(shape, 1.0)
cp.ShapeSetLayers(shape, notGrabableMask)
}
mass := cp.Float(1.0)
width := cp.Float(30.0)
height := width*2
for i := 0; i < 7; i++ {
for j := 0; j < 3; j++ {
pos := cp.V(cp.Float(i)*width - 150, cp.Float(j)*height - 150)
switch (C.Random()%3000)/1000 {
default:
tumbleAddCircle(space, cp.Vadd(pos, cp.V(0.0, (height - width)/2.0)), mass, width/2.0)
tumbleAddCircle(space, cp.Vadd(pos, cp.V(0.0, (width - height)/2.0)), mass, width/2.0)
case 0:
tumbleAddBox(space, pos, mass, width, height)
case 1:
tumbleAddSegment(space, pos, mass, width, height)
}
}
}
t.rogueBoxBody = rogueBoxBody
return space
}
func (t *tumble) Destroy(space *cp.Space) {
freeSpaceChildren(space)
cp.BodyFree(t.rogueBoxBody)
cp.SpaceFree(space)
}<|fim▁end|> | b := cp.V(-200, 200) |
<|file_name|>159. Longest Substring with At Most Two Distinct Characters.java<|end_file_name|><|fim▁begin|>public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int[] map = new int[128];
int count = 0, start = 0, end = 0, d = 0;
while (end < s.length()) {
if (map[s.charAt(end++)]++ == 0) count++;
while (count > 2) if(map[s.charAt(start++)]-- == 1) count--;<|fim▁hole|> d = Math.max(d, end - start);
}
return d;
}
}<|fim▁end|> | |
<|file_name|>package_spec.js<|end_file_name|><|fim▁begin|>var search = require('./helpers/search'),
authoring = require('./helpers/pages').authoring,<|fim▁hole|>
describe('package', () => {
beforeEach(() => {
monitoring.openMonitoring();
});
it('increment package version', () => {
monitoring.actionOnItem('Edit', 3, 0);
// Add item to current package.
monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
// Save package
authoring.save();
// Check version number.
authoring.showVersions();
expect(element.all(by.repeater('version in versions')).count()).toBe(2);
authoring.showVersions(); // close version panel
});
it('add to current package removed', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
// Open menu.
var menu = monitoring.openItemMenu(2, 0);
var header = menu.element(by.partialLinkText('Add to current'));
expect(header.isPresent()).toBeFalsy();
// Close menu.
menu.element(by.css('.dropdown__menu-close')).click();
});
it('reorder group package items', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
monitoring.actionOnItemSubmenu('Add to current', 'story', 3, 2);
// Reorder item on package
authoring.moveToGroup('MAIN', 0, 'STORY', 0);
expect(authoring.getGroupItems('MAIN').count()).toBe(0);
expect(authoring.getGroupItems('STORY').count()).toBe(2);
});
it('create package from multiple items', () => {
monitoring.selectItem(2, 0);
monitoring.selectItem(2, 1);
monitoring.createPackageFromItems();
expect(authoring.getGroupItems('MAIN').count()).toBe(2);
});
it('create package by combining an item with open item', () => {
monitoring.openAction(2, 1);
browser.sleep(500);
monitoring.actionOnItem('Combine with current', 3, 0);
expect(authoring.getGroupItems('MAIN').count()).toBe(2);
});
it('add multiple items to package', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.selectItem(2, 0);
monitoring.selectItem(3, 1);
monitoring.multiActionDropdown().click();
monitoring.addToCurrentMultipleItems();
expect(authoring.getGroupItems('MAIN').count()).toBe(2);
});
it('create package from published item', () => {
expect(monitoring.getTextItem(2, 0)).toBe('item5');
monitoring.actionOnItem('Edit', 2, 0);
authoring.writeText('some text');
authoring.save();
authoring.publish();
monitoring.showSearch();
search.setListView();
search.showCustomSearch();
search.toggleSearchTabs('filters');
search.toggleByType('text');
expect(search.getTextItem(0)).toBe('item5');
search.actionOnItem('Create package', 0);
expect(authoring.getGroupItems('MAIN').count()).toBe(1);
});
xit('can preview package in a package', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.actionOnItemSubmenu('Add to current', 'main', 3, 1);
authoring.save();
authoring.close();
monitoring.previewAction(3, 0);
// There is no preview in preview, SD-3319
});
});<|fim▁end|> | monitoring = require('./helpers/monitoring'); |
<|file_name|>proton.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from uuid import UUID
import uuid
try:
bytes()
except NameError:
bytes = str
from org.apache.qpid.proton import Proton, ProtonUnsupportedOperationException
from org.apache.qpid.proton import InterruptException as Interrupt
from org.apache.qpid.proton import TimeoutException as Timeout
from org.apache.qpid.proton.engine import \
Transport as JTransport, Sender as JSender, Receiver as JReceiver, \
Sasl, SslDomain as JSslDomain, \
EndpointState, TransportException
from org.apache.qpid.proton.message import \
MessageFormat, Message as JMessage
from org.apache.qpid.proton.codec import \
Data as JData
from org.apache.qpid.proton.messenger import MessengerException, Status
from org.apache.qpid.proton.amqp.transport import ErrorCondition, SenderSettleMode, ReceiverSettleMode
from org.apache.qpid.proton.amqp.messaging import Source, Target, Accepted, \
Rejected, Received, Modified, Released, AmqpValue
from org.apache.qpid.proton.amqp import UnsignedInteger, UnsignedLong, UnsignedByte, UnsignedShort, Symbol, \
Decimal32, Decimal64, Decimal128
from jarray import zeros, array
from java.util import EnumSet, UUID as JUUID, Date as JDate, HashMap
from java.nio import ByteBuffer
from java.lang import Character as JCharacter, String as JString, Integer as JInteger
from java.lang import NoClassDefFoundError
class Constant(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
class Skipped(Exception):
skipped = True
PENDING = "PENDING"
ACCEPTED = "ACCEPTED"
REJECTED = "REJECTED"
RELEASED = "RELEASED"
SETTLED = "SETTLED"
STATUSES = {
Status.ACCEPTED: ACCEPTED,
Status.REJECTED: REJECTED,
Status.PENDING: PENDING,
Status.RELEASED: RELEASED,
Status.SETTLED: SETTLED,
Status.UNKNOWN: None
}
MANUAL = "MANUAL"
AUTOMATIC = "AUTOMATIC"
API_LANGUAGE = "Java"
IMPLEMENTATION_LANGUAGE = "C"
if Proton.getDefaultImplementationType().name() == "PROTON_J":
IMPLEMENTATION_LANGUAGE = "Java"
class Endpoint(object):
LOCAL_UNINIT = 1
LOCAL_ACTIVE = 2
LOCAL_CLOSED = 4
REMOTE_UNINIT = 8
REMOTE_ACTIVE = 16
REMOTE_CLOSED = 32
def __init__(self):
self.condition = None
@property
def remote_condition(self):
return Condition(impl = self.impl.getRemoteCondition())
@property
def state(self):
local = self.impl.getLocalState()
remote = self.impl.getRemoteState()
result = 0
if (local == EndpointState.UNINITIALIZED):
result = result | self.LOCAL_UNINIT
elif (local == EndpointState.ACTIVE):
result = result | self.LOCAL_ACTIVE
elif (local == EndpointState.CLOSED):
result = result | self.LOCAL_CLOSED
if (remote == EndpointState.UNINITIALIZED):
result = result | self.REMOTE_UNINIT
elif (remote == EndpointState.ACTIVE):
result = result | self.REMOTE_ACTIVE
elif (remote == EndpointState.CLOSED):
result = result | self.REMOTE_CLOSED
return result
def _enums(self, mask):
local = []
if (self.LOCAL_UNINIT | mask):
local.append(EndpointState.UNINITIALIZED)
if (self.LOCAL_ACTIVE | mask):
local.append(EndpointState.ACTIVE)
if (self.LOCAL_CLOSED | mask):
local.append(EndpointState.CLOSED)
remote = []
if (self.REMOTE_UNINIT | mask):
remote.append(EndpointState.UNINITIALIZED)
if (self.REMOTE_ACTIVE | mask):
remote.append(EndpointState.ACTIVE)
if (self.REMOTE_CLOSED | mask):
remote.append(EndpointState.CLOSED)
return EnumSet.of(*local), EnumSet.of(*remote)
def open(self):
self.impl.open()
def close(self):
if self.condition is not None:
self.impl.setCondition(self.condition.impl)
self.impl.close()
class Condition(object):
def __init__(self, name=None, description=None, info=None, impl=None):
if impl is None:
impl = ErrorCondition(Symbol.valueOf(name), description)
if info is not None:
impl.setInfo(info)
self.impl = impl
def _get_name(self):
c = self.impl.getCondition()
if c is not None:
return c.toString()
def _set_name(self, n):
self.impl.setCondition(Symbol.valueOf(n))
name = property(_get_name, _set_name)
def _get_description(self):
return self.impl.getDescription()
def _set_description(self, d):
self.impl.setDescription(d)
description = property(_get_description, _set_description)
def _get_info(self):
return self.impl.getInfo()
def _set_info(self, i):
self.impl.setInfo(i)
info = property(_get_info, _get_description)
def __repr__(self):
return "Condition(%s)" % ", ".join([repr(x) for x in
(self.name, self.description, self.info)
if x])
def __eq__(self, o):
if not isinstance(o, Condition): return False
return self.impl.equals(o.impl)
def _2J(self):
return self.impl
def wrap_connection(impl):
if impl:
return impl.getContext()
else:
return None
class Connection(Endpoint):
def __init__(self):
Endpoint.__init__(self)
self.impl = Proton.connection()
self.impl.setContext(self)
self.desired_capabilities = None
self.offered_capabilities = None
self.properties = None
@property
def writable(self):
raise ProtonUnsupportedOperationException("Connection.writable")
def session(self):
return wrap_session(self.impl.session())
def session_head(self, mask):
return wrap_session(self.impl.sessionHead(*self._enums(mask)))
def link_head(self, mask):
return wrap_link(self.impl.linkHead(*self._enums(mask)))
@property
def work_head(self):
return wrap_delivery(self.impl.getWorkHead())
def _get_container(self):
return self.impl.getContainer()
def _set_container(self, container):
self.impl.setContainer(container)
container = property(_get_container, _set_container)
def _get_hostname(self):
return self.impl.getHostname()
def _set_hostname(self, hostname):
self.impl.setHostname(hostname)
hostname = property(_get_hostname, _set_hostname)
def _get_remote_container(self):
return self.impl.getRemoteContainer()
def _set_remote_container(self, container):
self.impl.setRemoteContainer(container)
remote_container = property(_get_remote_container, _set_remote_container)
def _get_remote_hostname(self):
return self.impl.getRemoteHostname()
def _set_remote_hostname(self, hostname):
self.impl.setRemoteHostname(hostname)
remote_hostname = property(_get_remote_hostname, _set_remote_hostname)
@property
def remote_offered_capabilities(self):
return convertToPyArray(Data.SYMBOL, self.impl.getRemoteOfferedCapabilities(),symbol)
@property
def remote_desired_capabilities(self):
return convertToPyArray(Data.SYMBOL, self.impl.getRemoteDesiredCapabilities(),symbol)
@property
def remote_properties(self):
return J2PY(self.impl.getRemoteProperties());
def open(self):
self.impl.setOfferedCapabilities(PY2J(self.offered_capabilities))
self.impl.setDesiredCapabilities(PY2J(self.desired_capabilities))
self.impl.setProperties(PY2J(self.properties))
Endpoint.open(self)
def wrap_session(impl):
# XXX
if impl: return Session(impl)
class Session(Endpoint):
def __init__(self, impl):
Endpoint.__init__(self)
self.impl = impl
@property
def connection(self):
return wrap_connection(self.impl.getConnection())
def sender(self, name):
return wrap_link(self.impl.sender(name))
def receiver(self, name):
return wrap_link(self.impl.receiver(name))
def _get_incoming_capacity(self):
return self.impl.getIncomingCapacity()
def _set_incoming_capacity(self, capacity):
self.impl.setIncomingCapacity(capacity)
incoming_capacity = property(_get_incoming_capacity, _set_incoming_capacity)
@property
def outgoing_bytes(self):
return self.impl.getOutgoingBytes()
@property
def incoming_bytes(self):
return self.impl.getIncomingBytes()
def wrap_link(impl):
if impl is None: return None
elif isinstance(impl, JSender):
return Sender(impl)
elif isinstance(impl, JReceiver):
return Receiver(impl)
else:
raise Exception("unknown type")
class Link(Endpoint):
SND_UNSETTLED = SenderSettleMode.UNSETTLED
SND_SETTLED = SenderSettleMode.SETTLED
SND_MIXED = SenderSettleMode.MIXED
RCV_FIRST = ReceiverSettleMode.FIRST
RCV_SECOND = ReceiverSettleMode.SECOND
def __init__(self, impl):
Endpoint.__init__(self)
self.impl = impl
@property
def source(self):
if self.impl.getSource() is None:
self.impl.setSource(Source())
return Terminus(self.impl.getSource())
@property
def target(self):
if self.impl.getTarget() is None:
self.impl.setTarget(Target())
return Terminus(self.impl.getTarget())
@property
def remote_source(self):
return Terminus(self.impl.getRemoteSource())
@property
def remote_target(self):
return Terminus(self.impl.getRemoteTarget())
@property
def session(self):
return wrap_session(self.impl.getSession())
def delivery(self, tag):
return wrap_delivery(self.impl.delivery(tag))
@property
def current(self):
return wrap_delivery(self.impl.current())
def advance(self):
return self.impl.advance()
@property
def unsettled(self):
return self.impl.getUnsettled()
@property
def credit(self):
return self.impl.getCredit()
@property
def available(self):
raise ProtonUnsupportedOperationException("Link.available")
@property
def queued(self):
return self.impl.getQueued()
def next(self, mask):
return wrap_link(self.impl.next(*self._enums(mask)))
@property
def name(self):
return self.impl.getName()
@property
def remote_snd_settle_mode(self):
return self.impl.getRemoteSenderSettleMode()
@property
def remote_rcv_settle_mode(self):
return self.impl.getRemoteReceiverSettleMode()
def _get_snd_settle_mode(self):
return self.impl.getSenderSettleMode()
def _set_snd_settle_mode(self, mode):
self.impl.setSenderSettleMode(mode)
snd_settle_mode = property(_get_snd_settle_mode, _set_snd_settle_mode)
def _get_rcv_settle_mode(self):
return self.impl.getReceiverSettleMode()
def _set_rcv_settle_mode(self, mode):
self.impl.setReceiverSettleMode(mode)
rcv_settle_mode = property(_get_rcv_settle_mode, _set_rcv_settle_mode)
def drained(self):
return self.impl.drained()
class DataDummy:
def format(self):
pass
def put_array(self, *args, **kwargs):
raise ProtonUnsupportedOperationException("Data.put_array")
class Terminus(object):
UNSPECIFIED = None
DIST_MODE_UNSPECIFIED = None
DIST_MODE_COPY = "copy"
DIST_MODE_MOVE = "move"
def __init__(self, impl):
self.impl = impl
self.type = None
self.timeout = None
self.durability = None
self.expiry_policy = None
self.properties = DataDummy()
self.outcomes = DataDummy()
self.filter = DataDummy()
self.capabilities = DataDummy()
def _get_address(self):
return self.impl.getAddress()
def _set_address(self, address):
self.impl.setAddress(address)
address = property(_get_address, _set_address)
def _get_timeout(self):
return self.impl.getTimeout()
def _set_timeout(self, t):
if t is not None:
t = UnsignedInteger(t)
return self.impl.setTimeout(t)
timeout = property(_get_timeout, _set_timeout)
def _is_dynamic(self):
return self.impl.getDynamic()
def _set_dynamic(self, dynamic):
self.impl.setDynamic(dynamic)
dynamic = property(_is_dynamic, _set_dynamic)
def _get_distribution_mode(self):
if isinstance(self.impl, Source):
sym = self.impl.getDistributionMode()
if sym is None:
return self.DIST_MODE_UNSPECIFIED
else:
return sym.toString()
else:
return self.DIST_MODE_UNSPECIFIED
def _set_distribution_mode(self, mode):
if isinstance(self.impl, Source):
if mode in [None, "copy", "move"]:
self.impl.setDistributionMode(Symbol.valueOf(mode))
else:
self.impl.setDistributionMode(None)
distribution_mode = property(_get_distribution_mode, _set_distribution_mode)
def copy(self, src):
self.address = src.address
self.timeout = src.timeout
self.dynamic = src.dynamic
self.distribution_mode = src.distribution_mode
class Sender(Link):
def offered(self, n):
raise ProtonUnsupportedOperationException("Sender.offered")
def send(self, bytes):
return self.impl.send(bytes, 0, len(bytes))
class Receiver(Link):
def flow(self, n):
self.impl.flow(n)
def drain(self, n):
self.impl.drain(n)
def draining(self):
return self.impl.draining()
def recv(self, size):
output = zeros(size, "b")
n = self.impl.recv(output, 0, size)
if n >= 0:
return output.tostring()[:n]
elif n == JTransport.END_OF_STREAM:
return None
else:
raise Exception(n)
class Disposition(object):
RECEIVED = 0x23
ACCEPTED = 0x24
REJECTED = 0x25
RELEASED = 0x26
MODIFIED = 0x27
def __init__(self):
self.type = 0
self._received = None
self._accepted = None
self._rejected = None
self._released = None
self._modified = None
def _get_section_number(self):
if self._received:
return J2PY(self._received.getSectionNumber())
else:
return 0
def _set_section_number(self, n):
if not self._received:
self._received = Received()
self._received.setSectionNumber(UnsignedInteger(n))
section_number = property(_get_section_number, _set_section_number)
def _get_section_offset(self):
if self._received:
return J2PY(self._received.getSectionOffset())
else:
return 0
def _set_section_offset(self, n):
if not self._received:
self._received = Received()
self._received.setSectionOffset(UnsignedLong(n))
section_offset = property(_get_section_offset, _set_section_offset)
def _get_failed(self):
if self._modified:
return self._modified.getDeliveryFailed()
else:
return False
def _set_failed(self, b):
if not self._modified:
self._modified = Modified()
self._modified.setDeliveryFailed(b)
failed = property(_get_failed, _set_failed)
def _get_undeliverable(self):
if self._modified:
return self._modified.getUndeliverableHere()
else:
return False
def _set_undeliverable(self, b):
if not self._modified:
self._modified = Modified()
self._modified.setUndeliverableHere(b)
undeliverable = property(_get_undeliverable, _set_undeliverable)
def _get_data(self):
return None
def _set_data(self, obj):
raise Skipped()
data = property(_get_data, _set_data)
def _get_annotations(self):
if self._modified:
return J2PY(self._modified.getMessageAnnotations())
else:
return None
def _set_annotations(self, obj):
if not self._modified:
self._modified = Modified()
self._modified.setMessageAnnotations(PY2J(obj))
annotations = property(_get_annotations, _set_annotations)
def _get_condition(self):
if self._rejected:
return Condition(impl = self._rejected.getError())
else:
return None
def _set_condition(self, obj):
if not self._rejected:
self._rejected = Rejected()
self._rejected.setError(obj._2J())
condition = property(_get_condition, _set_condition)
def _as_received(self):
if self._received is None:
self._received = Received()
return self._received
def _as_accepted(self):
if self._accepted is None:
self._accepted = Accepted.getInstance()
return self._accepted
def _as_rejected(self):
if self._rejected is None:
self._rejected = Rejected()
return self._rejected
def _as_released(self):
if self._released is None:
self._released = Released.getInstance()
return self._released
def _as_modified(self):
if self._modified is None:
self._modified = Modified()
return self._modified
PY2J = {
RECEIVED: _as_received,
ACCEPTED: _as_accepted,
REJECTED: _as_rejected,
RELEASED: _as_released,
MODIFIED: _as_modified
}
def _2J(self):
return self.PY2J[self.type](self)
def _from_received(self, s):
self.type = self.RECEIVED
self._received = s
def _from_accepted(self, s):
self.type = self.ACCEPTED
self._accepted = s
def _from_rejected(self, s):
self.type = self.REJECTED
self._rejected = s
def _from_released(self, s):
self.type = self.RELEASED
self._released = s
def _from_modified(self, s):
self.type = self.MODIFIED
self._modified = s
J2PY = {
Received: _from_received,
Accepted: _from_accepted,
Rejected: _from_rejected,
Released: _from_released,
Modified: _from_modified
}
def _2PY(self, impl):
self.J2PY[type(impl)](self, impl)
def wrap_delivery(impl):
if impl: return Delivery(impl)
class Delivery(object):
RECEIVED = Disposition.RECEIVED
ACCEPTED = Disposition.ACCEPTED
REJECTED = Disposition.REJECTED
RELEASED = Disposition.RELEASED
MODIFIED = Disposition.MODIFIED
def __init__(self, impl):
self.impl = impl
self.local = Disposition()
@property
def tag(self):
return self.impl.getTag().tostring()
@property
def writable(self):
return self.impl.isWritable()
@property
def readable(self):
return self.impl.isReadable()
@property
def updated(self):
return self.impl.isUpdated()
def update(self, disp):
self.local.type = disp
self.impl.disposition(self.local._2J())
@property
def remote(self):
d = Disposition()
d._2PY(self.impl.getRemoteState())
return d
@property
def remote_state(self):
return self.remote.type
@property
def local_state(self):
return self.local.type
def settle(self):
self.impl.settle()
@property
def settled(self):
return self.impl.remotelySettled()
@property
def work_next(self):
return wrap_delivery(self.impl.getWorkNext())
@property
def pending(self):
return self.impl.pending()
class Transport(object):
TRACE_OFF = 0
TRACE_RAW = 1
TRACE_FRM = 2
TRACE_DRV = 4
def __init__(self):
self.impl = Proton.transport()
self._ssl = None
self._sasl = None
def __del__(self):
if hasattr(self, ".impl") and self.impl:
pn_transport_free(self.impl)
if hasattr(self, "_sasl") and self._sasl:
# pn_transport_free deallocs the C sasl associated with the
# transport, so erase the reference if a SASL object was used.
self._sasl._sasl = None
self._sasl = None
if hasattr(self, "_ssl") and self._ssl:
# ditto the owned c SSL object
self._ssl._ssl = None
self._ssl = None
del self._trans
def trace(self, mask):
# XXX: self.impl.trace(mask)
pass
def bind(self, connection):
self.impl.bind(connection.impl)
def capacity(self):
return self.impl.capacity()
def push(self, bytes):
input_buffer = self.impl.tail()
input_buffer.put(bytes)
self.impl.process()
def close_tail(self):
self.impl.close_tail()
def pending(self):
return self.impl.pending()
def peek(self, size):
output_buffer = self.impl.head()
output_length = min(size, output_buffer.remaining())
output = zeros(output_length, "b")
output_buffer.mark()
output_buffer.get(output)
output_buffer.reset()
return output.tostring()
def pop(self, size):
self.impl.pop(size)
def close_head(self):
self.impl.close_head()
def output(self, size):
p = self.pending()
if p < 0:
return None
else:
out = self.peek(min(size, p))
self.pop(len(out))
return out
def input(self, bytes):
if not bytes:
self.close_tail()
return None
else:
c = self.capacity()
if (c < 0):
return None
trimmed = bytes[:c]
self.push(trimmed)
return len(trimmed)
def _get_max_frame_size(self):
return self.impl.getMaxFrameSize()
def _set_max_frame_size(self, value):
self.impl.setMaxFrameSize(value)
max_frame_size = property(_get_max_frame_size, _set_max_frame_size,
doc="""
Sets the maximum size for received frames (in bytes).
""")
@property
def remote_max_frame_size(self):
return self.impl.getRemoteMaxFrameSize()
# AMQP 1.0 idle-time-out
def _get_idle_timeout(self):
#return pn_transport_get_idle_timeout(self._trans)
raise ProtonUnsupportedOperationException("Transport.idle_timeout")
def _set_idle_timeout(self, value):
#pn_transport_set_idle_timeout(self._trans, value)
raise ProtonUnsupportedOperationException("Transport.idle_timeout")
idle_timeout = property(_get_idle_timeout, _set_idle_timeout,
doc="""
The idle timeout of the connection (in milliseconds).
""")
@property
def remote_idle_timeout(self):
#return pn_transport_get_remote_idle_timeout(self._trans)
raise ProtonUnsupportedOperationException("Transport.remote_idle_timeout")
@property
def frames_output(self):
#return pn_transport_get_frames_output(self._trans)
raise ProtonUnsupportedOperationException("Transport.frames_output")
@property
def frames_input(self):
#return pn_transport_get_frames_input(self._trans)
raise ProtonUnsupportedOperationException("Transport.frames_input")
def sasl(self):
# SASL factory (singleton for this transport)
if not self._sasl:
self._sasl = SASL(self)
return self._sasl
def ssl(self, domain=None, session_details=None):
# SSL factory (singleton for this transport)
if not self._ssl:
self._ssl = SSL(self, domain, session_details)
return self._ssl
class UnmappedType:
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return "UnmappedType(%s)" % self.msg
class ulong(long):
def __repr__(self):
return "ulong(%s)" % long.__repr__(self)
class timestamp(long):
def __repr__(self):
return "timestamp(%s)" % long.__repr__(self)
class symbol(unicode):
def __repr__(self):
return "symbol(%s)" % unicode.__repr__(self)
class char(unicode):
def __repr__(self):
return "char(%s)" % unicode.__repr__(self)
class Described(object):
def __init__(self, descriptor, value):
self.descriptor = descriptor
self.value = value
def __repr__(self):
return "Described(%r, %r)" % (self.descriptor, self.value)
def __eq__(self, o):
if isinstance(o, Described):
return self.descriptor == o.descriptor and self.value == o.value
else:
return False
UNDESCRIBED = Constant("UNDESCRIBED")
class Array(object):
def __init__(self, descriptor, type, *elements):
self.descriptor = descriptor
self.type = type
self.elements = elements
def __repr__(self):
if self.elements:
els = ", %s" % (", ".join(map(repr, self.elements)))
else:
els = ""
return "Array(%r, %r%s)" % (self.descriptor, self.type, els)
def __eq__(self, o):
if isinstance(o, Array):
return self.descriptor == o.descriptor and \
self.type == o.type and self.elements == o.elements
else:
return False
class Data(object):
NULL = JData.DataType.NULL;
BOOL = JData.DataType.BOOL;
UBYTE = JData.DataType.UBYTE;
BYTE = JData.DataType.BYTE;
USHORT = JData.DataType.USHORT;
SHORT = JData.DataType.SHORT;
UINT = JData.DataType.UINT;
INT = JData.DataType.INT;
CHAR = JData.DataType.CHAR;
ULONG = JData.DataType.ULONG;
LONG = JData.DataType.LONG;
TIMESTAMP = JData.DataType.TIMESTAMP;
FLOAT = JData.DataType.FLOAT;
DOUBLE = JData.DataType.DOUBLE;
DECIMAL32 = JData.DataType.DECIMAL32;
DECIMAL64 = JData.DataType.DECIMAL64;
DECIMAL128 = JData.DataType.DECIMAL128;
UUID = JData.DataType.UUID;
BINARY = JData.DataType.BINARY;
STRING = JData.DataType.STRING;
SYMBOL = JData.DataType.SYMBOL;
DESCRIBED = JData.DataType.DESCRIBED;
ARRAY = JData.DataType.ARRAY;
LIST = JData.DataType.LIST;
MAP = JData.DataType.MAP;
def __init__(self, capacity=16):
self._data = Proton.data(capacity)
def __del__(self):
if hasattr(self, "_data"):
pn_data_free(self._data)
del self._data
def clear(self):
self._data.clear()
def rewind(self):
self._data.rewind()
def next(self):
return self._data.next()
def prev(self):
return self._data.prev()
def enter(self):
return self._data.enter()
def exit(self):
return self._data.exit()
def lookup(self, name):
return self._data.lookup(name)
def narrow(self):
self._data.narrow()
def widen(self):
self._data.widen()
def type(self):
return self._data.type()
def encode(self):
b = self._data.encode()
return b.getArray().tostring()[b.getArrayOffset():b.getLength()]
def decode(self, encoded):
return self._data.decode(ByteBuffer.wrap(encoded))
def put_list(self):
self._data.putList()
def put_map(self):
self._data.putMap()
def put_array(self, described, element_type):
self._data.putArray(described, element_type)
def put_described(self):
self._data.putDescribed()
def put_null(self):
self._data.putNull()
def put_bool(self, b):
self._data.putBoolean(b)
def put_ubyte(self, ub):
self._data.putUnsignedByte(UnsignedByte.valueOf(ub))
def put_byte(self, b):
self._data.putByte(b)
def put_ushort(self, us):
self._data.putUnsignedShort(UnsignedShort.valueOf(us))
def put_short(self, s):
self._data.putShort(s)
def put_uint(self, ui):
self._data.putUnsignedInteger(UnsignedInteger.valueOf(ui))
def put_int(self, i):
self._data.putInt(i)
def put_char(self, c):
self._data.putChar(ord(c))
def put_ulong(self, ul):
self._data.putUnsignedLong(UnsignedLong.valueOf(ul))
def put_long(self, l):
self._data.putLong(l)
def put_timestamp(self, t):
self._data.putTimestamp(JDate(t))
def put_float(self, f):
self._data.putFloat(f)
def put_double(self, d):
self._data.putDouble(d)
def put_decimal32(self, d):
self._data.putDecimal32(Decimal32(d))
def put_decimal64(self, d):
self._data.putDecimal64(Decimal64(d))
def put_decimal128(self, d):
self._data.putDecimal128(Decimal128(d))
def put_uuid(self, u):
u = JUUID.fromString( str(u) )
self._data.putUUID(u)
def put_binary(self, b):
self._data.putBinary(b)
def put_string(self, s):
self._data.putString(s)
def put_symbol(self, s):
self._data.putSymbol(Symbol.valueOf(s))
def get_list(self):
return self._data.getList()
def get_map(self):
return self._data.getMap()
def get_array(self):
count = self._data.getArray()
described = self._data.isArrayDescribed()
type = self._data.getArrayType()
return count, described, type
def is_described(self):
return self._data.isDescribed()
def is_null(self):
return self._data.isNull()
def get_bool(self):
return self._data.getBoolean()
def get_ubyte(self):
return self._data.getUnsignedByte().shortValue()
def get_byte(self):
return self._data.getByte()
def get_ushort(self):
return self._data.getUnsignedShort().intValue()
def get_short(self):
return self._data.getShort()
def get_int(self):
return self._data.getInt()
def get_uint(self):
return self._data.getUnsignedInteger().longValue()
def get_char(self):
return char(unichr(self._data.getChar()))
def get_ulong(self):
return ulong(self._data.getUnsignedLong().longValue())
def get_long(self):
return self._data.getLong()
def get_timestamp(self):
return self._data.getTimestamp().getTime()
def get_float(self):
return self._data.getFloat()
def get_double(self):
return self._data.getDouble()
def get_decimal32(self):
return self._data.getDecimal32().getBits()
def get_decimal64(self):
return self._data.getDecimal64().getBits()
def get_decimal128(self):
return self._data.getDecimal128().asBytes().tostring()
def get_uuid(self):
return UUID(self._data.getUUID().toString() )
def get_binary(self):
b = self._data.getBinary()
return b.getArray().tostring()[b.getArrayOffset():b.getArrayOffset()+b.getLength()]
def get_string(self):
return self._data.getString()
def get_symbol(self):
return symbol(self._data.getSymbol().toString())
def put_dict(self, d):
self.put_map()
self.enter()
try:
for k, v in d.items():
self.put_object(k)
self.put_object(v)
finally:
self.exit()
def get_dict(self):
if self.enter():
try:
result = {}
while self.next():
k = self.get_object()
if self.next():
v = self.get_object()
else:
v = None
result[k] = v
finally:
self.exit()
return result
def put_sequence(self, s):
self.put_list()
self.enter()
try:
for o in s:
self.put_object(o)
finally:
self.exit()
def get_sequence(self):
if self.enter():
try:
result = []
while self.next():
result.append(self.get_object())
finally:
self.exit()
return result
def get_py_described(self):
if self.enter():
try:
self.next()
descriptor = self.get_object()
self.next()
value = self.get_object()
finally:
self.exit()
return Described(descriptor, value)
def put_py_described(self, d):
self.put_described()
self.enter()
try:
self.put_object(d.descriptor)
self.put_object(d.value)
finally:
self.exit()
def get_py_array(self):
count, described, type = self.get_array()
if self.enter():
try:
if described:
self.next()
descriptor = self.get_object()
else:
descriptor = UNDESCRIBED
elements = []
while self.next():
elements.append(self.get_object())
finally:
self.exit()
return Array(descriptor, type, *elements)
def put_py_array(self, a):
self.put_array(a.descriptor != UNDESCRIBED, a.type)
self.enter()
try:
for e in a.elements:
self.put_object(e)
finally:
self.exit()
put_mappings = {
None.__class__: lambda s, _: s.put_null(),
bool: put_bool,
dict: put_dict,
list: put_sequence,
tuple: put_sequence,
unicode: put_string,
bytes: put_binary,
symbol: put_symbol,
int: put_int,
char: put_char,
long: put_long,
ulong: put_ulong,
timestamp: put_timestamp,
float: put_double,
uuid.UUID: put_uuid,
Described: put_py_described,
Array: put_py_array
}
get_mappings = {
NULL: lambda s: None,
BOOL: get_bool,
BYTE: get_byte,
UBYTE: get_ubyte,
SHORT: get_short,
USHORT: get_ushort,
INT: get_int,
UINT: get_uint,
CHAR: get_char,
LONG: get_long,
ULONG: get_ulong,
TIMESTAMP: get_timestamp,
FLOAT: get_float,
DOUBLE: get_double,
DECIMAL32: get_decimal32,
DECIMAL64: get_decimal64,
DECIMAL128: get_decimal128,
UUID: get_uuid,
BINARY: get_binary,
STRING: get_string,
SYMBOL: get_symbol,
DESCRIBED: get_py_described,
ARRAY: get_py_array,
LIST: get_sequence,
MAP: get_dict
}
def put_object(self, obj):
putter = self.put_mappings[obj.__class__]
putter(self, obj)
<|fim▁hole|> type = self.type()
if type is None: return None
getter = self.get_mappings.get(type)
if getter:
return getter(self)
else:
self.dump()
return UnmappedType(str(type))
def copy(self, src):
self._data.copy(src._data)
def format(self):
return self._data.toString()
class Messenger(object):
def __init__(self, name=None):
if name:
self.impl = Proton.messenger(name)
else:
self.impl = Proton.messenger()
def route(self, pattern, address):
self.impl.route(pattern, address)
def rewrite(self, pattern, address):
self.impl.rewrite(pattern, address)
def start(self):
self.impl.start()
def stop(self):
self.impl.stop()
@property
def stopped(self):
return self.impl.stopped()
def subscribe(self, source):
self.impl.subscribe(source)
def put(self, message):
self.impl.put(message.impl)
return self.impl.outgoingTracker()
def send(self, n=-1):
self.impl.send(n)
def recv(self, n=-1):
self.impl.recv(n)
@property
def receiving(self):
return self.impl.receiving()
def work(self, timeout=None):
if timeout is None:
t = -1
else:
t = long(1000*timeout)
try:
err = self.impl.work(t)
except Timeout, e:
return False
return err
def interrupt(self):
self.impl.interrupt()
def get(self, message=None):
result = self.impl.get()
if message and result:
message.impl = result
return self.impl.incomingTracker()
@property
def outgoing(self):
return self.impl.outgoing()
@property
def incoming(self):
return self.impl.incoming()
def _get_timeout(self):
t = self.impl.getTimeout()
if t == -1:
return None
else:
return float(t)/1000
def _set_timeout(self, timeout):
if timeout is None:
t = -1
else:
t = long(1000*timeout)
self.impl.setTimeout(t)
timeout = property(_get_timeout, _set_timeout)
def _is_blocking(self):
return self.impl.isBlocking()
def _set_blocking(self, b):
self.impl.setBlocking(b)
blocking = property(_is_blocking, _set_blocking)
def accept(self, tracker=None):
if tracker is None:
tracker = self.impl.incomingTracker()
flags = self.impl.CUMULATIVE
else:
flags = 0
self.impl.accept(tracker, flags)
def reject(self, tracker=None):
if tracker is None:
tracker = self.impl.incomingTracker()
flags = self.impl.CUMULATIVE
else:
flags = 0
self.impl.reject(tracker, flags)
def settle(self, tracker=None):
if tracker is None:
tracker = self.impl.outgoingTracker()
flags = self.impl.CUMULATIVE
else:
flags = 0
self.impl.settle(tracker, flags)
def status(self, tracker):
return STATUSES[self.impl.getStatus(tracker)]
def _get_incoming_window(self):
return self.impl.getIncomingWindow()
def _set_incoming_window(self, window):
self.impl.setIncomingWindow(window)
incoming_window = property(_get_incoming_window, _set_incoming_window)
def _get_outgoing_window(self):
return self.impl.getOutgoingWindow()
def _set_outgoing_window(self, window):
self.impl.setOutgoingWindow(window)
outgoing_window = property(_get_outgoing_window, _set_outgoing_window)
def _get_certificate(self):
raise Skipped()
def _set_certificate(self, xxx):
raise Skipped()
certificate = property(_get_certificate, _set_certificate)
def buffered(self, tracker):
raise Skipped()
class Message(object):
AMQP = MessageFormat.AMQP
TEXT = MessageFormat.TEXT
DATA = MessageFormat.DATA
JSON = MessageFormat.JSON
DEFAULT_PRIORITY = JMessage.DEFAULT_PRIORITY
def __init__(self):
self.impl = Proton.message()
def clear(self):
self.impl.clear()
def save(self):
saved = self.impl.save()
if saved is None:
saved = ""
elif not isinstance(saved, unicode):
saved = saved.tostring()
return saved
def load(self, data):
self.impl.load(data)
def encode(self):
size = 1024
output = zeros(size, "b")
while True:
n = self.impl.encode(output, 0, size)
# XXX: need to check for overflow
if n > 0:
return output.tostring()[:n]
else:
raise Exception(n)
def decode(self, data):
self.impl.decode(data,0,len(data))
def _get_id(self):
id = self.impl.getMessageId()
if isinstance(id, JUUID):
id = UUID( id.toString() )
return id
def _set_id(self, value):
if isinstance(value, UUID):
value = JUUID.fromString( str(value) )
return self.impl.setMessageId(value)
id = property(_get_id, _set_id)
def _get_correlation_id(self):
id = self.impl.getCorrelationId()
if isinstance(id, JUUID):
id = UUID( id.toString() )
return id
def _set_correlation_id(self, value):
if isinstance(value, UUID):
value = JUUID.fromString( str(value) )
return self.impl.setCorrelationId(value)
correlation_id = property(_get_correlation_id, _set_correlation_id)
def _get_ttl(self):
return self.impl.getTtl()
def _set_ttl(self, ttl):
self.impl.setTtl(ttl)
ttl = property(_get_ttl, _set_ttl)
def _get_priority(self):
return self.impl.getPriority()
def _set_priority(self, priority):
self.impl.setPriority(priority)
priority = property(_get_priority, _set_priority)
def _get_address(self):
return self.impl.getAddress()
def _set_address(self, address):
self.impl.setAddress(address)
address = property(_get_address, _set_address)
def _get_subject(self):
return self.impl.getSubject()
def _set_subject(self, subject):
self.impl.setSubject(subject)
subject = property(_get_subject, _set_subject)
def _get_user_id(self):
u = self.impl.getUserId()
if u is None: return ""
else: return u.tostring()
def _set_user_id(self, user_id):
self.impl.setUserId(user_id)
user_id = property(_get_user_id, _set_user_id)
def _get_reply_to(self):
return self.impl.getReplyTo()
def _set_reply_to(self, reply_to):
self.impl.setReplyTo(reply_to)
reply_to = property(_get_reply_to, _set_reply_to)
def _get_reply_to_group_id(self):
return self.impl.getReplyToGroupId()
def _set_reply_to_group_id(self, reply_to_group_id):
self.impl.setReplyToGroupId(reply_to_group_id)
reply_to_group_id = property(_get_reply_to_group_id, _set_reply_to_group_id)
def _get_group_id(self):
return self.impl.getGroupId()
def _set_group_id(self, group_id):
self.impl.setGroupId(group_id)
group_id = property(_get_group_id, _set_group_id)
def _get_group_sequence(self):
return self.impl.getGroupSequence()
def _set_group_sequence(self, group_sequence):
self.impl.setGroupSequence(group_sequence)
group_sequence = property(_get_group_sequence, _set_group_sequence)
def _is_first_acquirer(self):
return self.impl.isFirstAcquirer()
def _set_first_acquirer(self, b):
self.impl.setFirstAcquirer(b)
first_acquirer = property(_is_first_acquirer, _set_first_acquirer)
def _get_expiry_time(self):
return self.impl.getExpiryTime()
def _set_expiry_time(self, expiry_time):
self.impl.setExpiryTime(expiry_time)
expiry_time = property(_get_expiry_time, _set_expiry_time)
def _is_durable(self):
return self.impl.isDurable()
def _set_durable(self, durable):
self.impl.setDurable(durable)
durable = property(_is_durable, _set_durable)
def _get_delivery_count(self):
return self.impl.getDeliveryCount()
def _set_delivery_count(self, delivery_count):
self.impl.setDeliveryCount(delivery_count)
delivery_count = property(_get_delivery_count, _set_delivery_count)
def _get_creation_time(self):
return self.impl.getCreationTime()
def _set_creation_time(self, creation_time):
self.impl.setCreationTime(creation_time)
creation_time = property(_get_creation_time, _set_creation_time)
def _get_content_type(self):
return self.impl.getContentType()
def _set_content_type(self, content_type):
self.impl.setContentType(content_type)
content_type = property(_get_content_type, _set_content_type)
def _get_content_encoding(self):
return self.impl.getContentEncoding()
def _set_content_encoding(self, content_encoding):
self.impl.setContentEncoding(content_encoding)
content_encoding = property(_get_content_encoding, _set_content_encoding)
def _get_format(self):
return self.impl.getFormat()
def _set_format(self, format):
self.impl.setMessageFormat(format)
format = property(_get_format, _set_format)
def _get_body(self):
body = self.impl.getBody()
if isinstance(body, AmqpValue):
return body.getValue()
else:
return body
def _set_body(self, body):
self.impl.setBody(AmqpValue(body))
body = property(_get_body, _set_body)
class SASL(object):
OK = Sasl.PN_SASL_OK
AUTH = Sasl.PN_SASL_AUTH
def __new__(cls, transport):
"""Enforce a singleton SASL object per Transport"""
if not transport._sasl:
obj = super(SASL, cls).__new__(cls)
obj._sasl = transport.impl.sasl()
transport._sasl = obj
return transport._sasl
def mechanisms(self, mechanisms):
self._sasl.setMechanisms(mechanisms.split())
def client(self):
self._sasl.client()
def server(self):
self._sasl.server()
def send(self, data):
self._sasl.send(data, 0, len(data))
def recv(self):
size = 4096
output = zeros(size, "b")
n = self._sasl.recv(output, 0, size)
if n >= 0:
return output.tostring()[:n]
elif n == JTransport.END_OF_STREAM:
return None
else:
raise Exception(n)
def _get_outcome(self):
value = self._sasl.getOutcome()
if value == Sasl.PN_SASL_NONE:
return None
else:
return value
def _set_outcome(self, outcome):
self.impl.setOutcome(outcome)
outcome = property(_get_outcome, _set_outcome)
def done(self, outcome):
self._sasl.done(outcome)
def plain(self, user, password):
self._sasl.plain(user,password)
class SSLException(Exception):
pass
class SSLUnavailable(SSLException):
pass
class SSLDomain(object):
MODE_SERVER = JSslDomain.Mode.SERVER
MODE_CLIENT = JSslDomain.Mode.CLIENT
VERIFY_PEER = JSslDomain.VerifyMode.VERIFY_PEER
VERIFY_PEER_NAME = JSslDomain.VerifyMode.VERIFY_PEER_NAME
ANONYMOUS_PEER = JSslDomain.VerifyMode.ANONYMOUS_PEER
def __init__(self, mode):
try:
self._domain = Proton.sslDomain()
except NoClassDefFoundError, e:
raise SSLUnavailable()
self._domain.init(mode)
def set_credentials(self, cert_file, key_file, password):
self._domain.setCredentials(cert_file, key_file, password)
def set_trusted_ca_db(self, certificate_db):
self._domain.setTrustedCaDb(certificate_db)
def set_peer_authentication(self, verify_mode, trusted_CAs=None):
# TODO the method calls (setTrustedCaDb/setPeerAuthentication) have to occur in
# that order otherwise tests fail with proton-jni. It is not clear yet why.
if trusted_CAs is not None:
self._domain.setTrustedCaDb(trusted_CAs)
self._domain.setPeerAuthentication(verify_mode)
def allow_unsecured_client(self, allow_unsecured = True):
self._domain.allowUnsecuredClient(allow_unsecured)
class SSLSessionDetails(object):
def __init__(self, session_id):
self._session_details = Proton.sslPeerDetails(session_id, 1)
class SSL(object):
def __new__(cls, transport, domain, session_details=None):
"""Enforce a singleton SSL object per Transport"""
if transport._ssl:
# unfortunately, we've combined the allocation and the configuration in a
# single step. So catch any attempt by the application to provide what
# may be a different configuration than the original (hack)
ssl = transport._ssl
if (domain and (ssl._domain is not domain) or
session_details and (ssl._session_details is not session_details)):
raise SSLException("Cannot re-configure existing SSL object!")
else:
obj = super(SSL, cls).__new__(cls)
obj._domain = domain
obj._session_details = session_details
internal_session_details = None
if session_details:
internal_session_details = session_details._session_details
obj._ssl = transport.impl.ssl(domain._domain, internal_session_details)
transport._ssl = obj
return transport._ssl
def __init__(self, transport, domain, session_details=None):
internal_session_details = None
if session_details:
internal_session_details = session_details._session_details
self._ssl = transport.impl.ssl(domain._domain, internal_session_details)
self._session_details = session_details
def get_session_details(self):
return self._session_details
def cipher_name(self):
return self._ssl.getCipherName()
def protocol_name(self):
return self._ssl.getProtocolName()
def _set_peer_hostname(self, hostname):
self._ssl.setPeerHostname(hostname)
def _get_peer_hostname(self):
return self._ssl.getPeerHostname()
peer_hostname = property(_get_peer_hostname, _set_peer_hostname)
class Driver(object):
""" Proton-c platform abstraction - not needed."""
def __init__(self, *args, **kwargs):
raise ProtonUnsupportedOperationException("Driver")
class Connector(object):
""" Proton-c platform abstraction - not needed."""
def __init__(self, *args, **kwargs):
raise ProtonUnsupportedOperationException("Connector")
class Listener(object):
""" Proton-c platform abstraction - not needed."""
def __init__(self, *args, **kwargs):
raise ProtonUnsupportedOperationException("Listener")
def convertToPyArray(t,a,f):
if a == None or len(a) == 0:
return None
return Array(UNDESCRIBED, t, *map(f,a))
arrayElementMappings = {
JData.DataType.SYMBOL: lambda s: Symbol.valueOf(s)
}
arrayTypeMappings = {
JData.DataType.SYMBOL: Symbol
}
conversions_J2PY = {
dict: lambda d: dict([(J2PY(k), J2PY(v)) for k, v in d.items()]),
HashMap: lambda m: dict([(J2PY(e.getKey()), J2PY(e.getValue())) for e in m.entrySet()]),
list: lambda l: [J2PY(x) for x in l],
Symbol: lambda s: symbol(s.toString()),
UnsignedInteger: lambda n: n.longValue(),
UnsignedLong: lambda n: n.longValue()
}
conversions_PY2J = {
dict: lambda d: dict([(PY2J(k), PY2J(v)) for k, v in d.items()]),
list: lambda l: [PY2J(x) for x in l],
symbol: lambda s: Symbol.valueOf(s),
Array: lambda a: array(map(arrayElementMappings[a.type], a.elements),
arrayTypeMappings[a.type])
}
def identity(x): return x
def J2PY(obj):
result = conversions_J2PY.get(type(obj), identity)(obj)
return result
def PY2J(obj):
result = conversions_PY2J.get(type(obj), identity)(obj)
return result
__all__ = [
"ACCEPTED",
"Array",
"API_LANGUAGE",
"IMPLEMENTATION_LANGUAGE",
"MANUAL",
"PENDING",
"REJECTED",
"RELEASED",
"SETTLED",
"char",
"Condition",
"Connection",
"Connector",
"Data",
"Delivery",
"Disposition",
"Described",
"Driver",
"Endpoint",
"Link",
"Listener",
"Message",
"MessageException",
"Messenger",
"MessengerException",
"ProtonException",
"Receiver",
"SASL",
"Sender",
"Session",
"SSL",
"SSLDomain",
"SSLException",
"SSLSessionDetails",
"SSLUnavailable",
"symbol",
"timestamp",
"Terminus",
"Timeout",
"Interrupt",
"Transport",
"TransportException",
"ulong",
"UNDESCRIBED"]<|fim▁end|> | def get_object(self): |
<|file_name|>Item.js<|end_file_name|><|fim▁begin|>/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.old.Item");
dojo.require("dojo.data.old.Observable");
dojo.require("dojo.data.old.Value");
dojo.require("dojo.lang.common");
dojo.require("dojo.lang.assert");
dojo.data.old.Item = function (dataProvider) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional:true});
dojo.data.old.Observable.call(this);
this._dataProvider = dataProvider;
this._dictionaryOfAttributeValues = {};<|fim▁hole|>};
dojo.inherits(dojo.data.old.Item, dojo.data.old.Observable);
dojo.data.old.Item.compare = function (itemOne, itemTwo) {
dojo.lang.assertType(itemOne, dojo.data.old.Item);
if (!dojo.lang.isOfType(itemTwo, dojo.data.old.Item)) {
return -1;
}
var nameOne = itemOne.getName();
var nameTwo = itemTwo.getName();
if (nameOne == nameTwo) {
var attributeArrayOne = itemOne.getAttributes();
var attributeArrayTwo = itemTwo.getAttributes();
if (attributeArrayOne.length != attributeArrayTwo.length) {
if (attributeArrayOne.length > attributeArrayTwo.length) {
return 1;
} else {
return -1;
}
}
for (var i in attributeArrayOne) {
var attribute = attributeArrayOne[i];
var arrayOfValuesOne = itemOne.getValues(attribute);
var arrayOfValuesTwo = itemTwo.getValues(attribute);
dojo.lang.assert(arrayOfValuesOne && (arrayOfValuesOne.length > 0));
if (!arrayOfValuesTwo) {
return 1;
}
if (arrayOfValuesOne.length != arrayOfValuesTwo.length) {
if (arrayOfValuesOne.length > arrayOfValuesTwo.length) {
return 1;
} else {
return -1;
}
}
for (var j in arrayOfValuesOne) {
var value = arrayOfValuesOne[j];
if (!itemTwo.hasAttributeValue(value)) {
return 1;
}
}
return 0;
}
} else {
if (nameOne > nameTwo) {
return 1;
} else {
return -1;
}
}
};
dojo.data.old.Item.prototype.toString = function () {
var arrayOfStrings = [];
var attributes = this.getAttributes();
for (var i in attributes) {
var attribute = attributes[i];
var arrayOfValues = this.getValues(attribute);
var valueString;
if (arrayOfValues.length == 1) {
valueString = arrayOfValues[0];
} else {
valueString = "[";
valueString += arrayOfValues.join(", ");
valueString += "]";
}
arrayOfStrings.push(" " + attribute + ": " + valueString);
}
var returnString = "{ ";
returnString += arrayOfStrings.join(",\n");
returnString += " }";
return returnString;
};
dojo.data.old.Item.prototype.compare = function (otherItem) {
return dojo.data.old.Item.compare(this, otherItem);
};
dojo.data.old.Item.prototype.isEqual = function (otherItem) {
return (this.compare(otherItem) == 0);
};
dojo.data.old.Item.prototype.getName = function () {
return this.get("name");
};
dojo.data.old.Item.prototype.get = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
return literalOrValueOrArray.getValue();
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
var dojoDataValue = literalOrValueOrArray[0];
return dojoDataValue.getValue();
}
return literalOrValueOrArray;
};
dojo.data.old.Item.prototype.getValue = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
return literalOrValueOrArray;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
var dojoDataValue = literalOrValueOrArray[0];
return dojoDataValue;
}
var literal = literalOrValueOrArray;
dojoDataValue = new dojo.data.old.Value(literal);
this._dictionaryOfAttributeValues[attributeId] = dojoDataValue;
return dojoDataValue;
};
dojo.data.old.Item.prototype.getValues = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
var array = [literalOrValueOrArray];
this._dictionaryOfAttributeValues[attributeId] = array;
return array;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
return literalOrValueOrArray;
}
var literal = literalOrValueOrArray;
var dojoDataValue = new dojo.data.old.Value(literal);
array = [dojoDataValue];
this._dictionaryOfAttributeValues[attributeId] = array;
return array;
};
dojo.data.old.Item.prototype.load = function (attributeId, value) {
this._dataProvider.registerAttribute(attributeId);
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
this._dictionaryOfAttributeValues[attributeId] = value;
return;
}
if (!(value instanceof dojo.data.old.Value)) {
value = new dojo.data.old.Value(value);
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
var array = [literalOrValueOrArray, value];
this._dictionaryOfAttributeValues[attributeId] = array;
return;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
literalOrValueOrArray.push(value);
return;
}
var literal = literalOrValueOrArray;
var dojoDataValue = new dojo.data.old.Value(literal);
array = [dojoDataValue, value];
this._dictionaryOfAttributeValues[attributeId] = array;
};
dojo.data.old.Item.prototype.set = function (attributeId, value) {
this._dataProvider.registerAttribute(attributeId);
this._dictionaryOfAttributeValues[attributeId] = value;
this._dataProvider.noteChange(this, attributeId, value);
};
dojo.data.old.Item.prototype.setValue = function (attributeId, value) {
this.set(attributeId, value);
};
dojo.data.old.Item.prototype.addValue = function (attributeId, value) {
this.load(attributeId, value);
this._dataProvider.noteChange(this, attributeId, value);
};
dojo.data.old.Item.prototype.setValues = function (attributeId, arrayOfValues) {
dojo.lang.assertType(arrayOfValues, Array);
this._dataProvider.registerAttribute(attributeId);
var finalArray = [];
this._dictionaryOfAttributeValues[attributeId] = finalArray;
for (var i in arrayOfValues) {
var value = arrayOfValues[i];
if (!(value instanceof dojo.data.old.Value)) {
value = new dojo.data.old.Value(value);
}
finalArray.push(value);
this._dataProvider.noteChange(this, attributeId, value);
}
};
dojo.data.old.Item.prototype.getAttributes = function () {
var arrayOfAttributes = [];
for (var key in this._dictionaryOfAttributeValues) {
arrayOfAttributes.push(this._dataProvider.getAttribute(key));
}
return arrayOfAttributes;
};
dojo.data.old.Item.prototype.hasAttribute = function (attributeId) {
return (attributeId in this._dictionaryOfAttributeValues);
};
dojo.data.old.Item.prototype.hasAttributeValue = function (attributeId, value) {
var arrayOfValues = this.getValues(attributeId);
for (var i in arrayOfValues) {
var candidateValue = arrayOfValues[i];
if (candidateValue.isEqual(value)) {
return true;
}
}
return false;
};<|fim▁end|> | |
<|file_name|>ResourcesTester.java<|end_file_name|><|fim▁begin|>package net.community.chest.test.gui;
import java.io.BufferedReader;
import java.io.PrintStream;
import net.community.chest.Triplet;
import net.community.chest.awt.dom.converter.InsetsValueInstantiator;
import net.community.chest.awt.layout.gridbag.ExtendedGridBagConstraints;
import net.community.chest.awt.layout.gridbag.GridBagGridSizingType;
import net.community.chest.awt.layout.gridbag.GridBagXYValueStringInstantiator;
import net.community.chest.dom.DOMUtils;
import net.community.chest.test.TestBase;
import org.w3c.dom.Element;
/**
* <P>Copyright 2007 as per GPLv2</P>
*
* @author Lyor G.
* @since Aug 7, 2007 2:09:18 PM
*/
public class ResourcesTester extends TestBase {
private static final int testElementDataParsing (final PrintStream out, final BufferedReader in, final String elemData, final Element elem)
{
for ( ; ; )
{
out.println(elemData);
try
{
final ExtendedGridBagConstraints gbc=new ExtendedGridBagConstraints(elem);
out.println("\tgridx=" + (gbc.isAbsoluteGridX() ? String.valueOf(gbc.gridx) : GridBagXYValueStringInstantiator.RELATIVE_VALUE));
out.println("\tgridy=" + (gbc.isAbsoluteGridY() ? String.valueOf(gbc.gridy) : GridBagXYValueStringInstantiator.RELATIVE_VALUE));
final GridBagGridSizingType wt=gbc.getGridWithType(), ht=gbc.getGridHeightType();
out.println("\tgridwidth=" + ((null == wt) ? String.valueOf(gbc.gridwidth) : wt.name()));
out.println("\tgridheight=" + ((null == ht) ? String.valueOf(gbc.gridheight) : ht.name()));
out.println("\tfill=" + gbc.getFillType());
out.println("\tipadx=" + gbc.ipadx);
out.println("\tipady=" + gbc.ipady);
out.println("\tinsets=" + InsetsValueInstantiator.toString(gbc.insets));
out.println("\tanchor=" + gbc.getAnchorType());
out.println("\tweightx=" + gbc.weightx);
out.println("\tweighty=" + gbc.weighty);
}
catch(Exception e)
{
System.err.println("testElementDataParsing(" + elemData + ") " + e.getClass().getName() + ": " + e.getMessage());
}
final String ans=getval(out, in, "again (y)/[n]");
if ((null == ans) || (ans.length() <= 0) || (Character.toLowerCase(ans.charAt(0)) != 'y'))
break;
}
return 0;
}
// each argument is an XML element string to be parsed
private static final int testGridBagConstraintsParsing (final PrintStream out, final BufferedReader in, final String ... args)
{
final int numArgs=(null == args) ? 0 : args.length;
for (int aIndex=0; ; aIndex++)
{
final String elemData=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "XML element data (or Quit)");
if ((null == elemData) || (elemData.length() <= 0))
continue;
if (isQuit(elemData)) break;
try<|fim▁hole|> final Triplet<? extends Element,?,?> pe=
DOMUtils.parseElementString(elemData);
testElementDataParsing(out, in, elemData, (null == pe) ? null : pe.getV1());
}
catch(Exception e)
{
System.err.println("testGridBagConstraintsParsing(" + elemData + ") " + e.getClass().getName() + ": " + e.getMessage());
}
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
public static void main (String[] args)
{
final BufferedReader in=getStdin();
final int nErr=testGridBagConstraintsParsing(System.out, in, args);
if (nErr != 0)
System.err.println("test failed (err=" + nErr + ")");
else
System.out.println("OK");
}
}<|fim▁end|> | { |
<|file_name|>default_census_cat_transforms.py<|end_file_name|><|fim▁begin|># PopGen 1.1 is A Synthetic Population Generator for Advanced
# Microsimulation Models of Travel Demand
# Copyright (C) 2009, Arizona State University
# See PopGen/License
DEFAULT_PERSON_PUMS2000_QUERIES = [ "alter table person_pums add column agep bigint",
"alter table person_pums add column gender bigint",
"alter table person_pums add column race bigint",
"alter table person_pums add column employment bigint",
"update person_pums set agep = 1 where age < 5",
"update person_pums set agep = 2 where age >= 5 and age < 15",
"update person_pums set agep = 3 where age >= 15 and age < 25",
"update person_pums set agep = 4 where age >= 25 and age < 35",
"update person_pums set agep = 5 where age >= 35 and age < 45",
"update person_pums set agep = 6 where age >= 45 and age < 55",
"update person_pums set agep = 7 where age >= 55 and age < 65",
"update person_pums set agep = 8 where age >= 65 and age < 75",
"update person_pums set agep = 9 where age >= 75 and age < 85",
"update person_pums set agep = 10 where age >= 85",
"update person_pums set gender = sex",
"update person_pums set race = 1 where race1 = 1",
"update person_pums set race = 2 where race1 = 2",
"update person_pums set race = 3 where race1 >=3 and race1 <= 5",
"update person_pums set race = 4 where race1 = 6",
"update person_pums set race = 5 where race1 = 7",
"update person_pums set race = 6 where race1 = 8",
"update person_pums set race = 7 where race1 = 9",
"update person_pums set employment = 1 where esr = 0",
"update person_pums set employment = 2 where esr = 1 or esr = 2 or esr = 4 or esr = 5",
"update person_pums set employment = 3 where esr = 3",
"update person_pums set employment = 4 where esr = 6",
"drop table person_sample",
"create table person_sample select state, pumano, hhid, serialno, pnum, agep, gender, race, employment, relate from person_pums",
"alter table person_sample add index(serialno, pnum)",
"drop table hhld_sample_temp",
"alter table hhld_sample drop column hhldrage",
"alter table hhld_sample rename to hhld_sample_temp",
"drop table hhld_sample",
"create table hhld_sample select hhld_sample_temp.*, agep as hhldrage from hhld_sample_temp left join person_sample using(serialno) where relate = 1",
"alter table hhld_sample add index(serialno)",
"update hhld_sample set hhldrage = 1 where hhldrage <=7 ",
"update hhld_sample set hhldrage = 2 where hhldrage >7"]
DEFAULT_PERSON_PUMSACS_QUERIES = ["alter table person_pums change agep age bigint",
"alter table person_pums change puma pumano bigint",
"alter table person_pums change rac1p race1 bigint",
"alter table person_pums change st state bigint",
"alter table person_pums change sporder pnum bigint",
"alter table person_pums change rel relate bigint",
"alter table person_pums add column agep bigint",
"alter table person_pums add column gender bigint",
"alter table person_pums add column race bigint",
"alter table person_pums add column employment bigint",
"update person_pums set agep = 1 where age < 5",
"update person_pums set agep = 2 where age >= 5 and age < 15",
"update person_pums set agep = 3 where age >= 15 and age < 25",
"update person_pums set agep = 4 where age >= 25 and age < 35",
"update person_pums set agep = 5 where age >= 35 and age < 45",
"update person_pums set agep = 6 where age >= 45 and age < 55",
"update person_pums set agep = 7 where age >= 55 and age < 65",
"update person_pums set agep = 8 where age >= 65 and age < 75",
"update person_pums set agep = 9 where age >= 75 and age < 85",
"update person_pums set agep = 10 where age >= 85",
"update person_pums set gender = sex",
"update person_pums set race = 1 where race1 = 1",
"update person_pums set race = 2 where race1 = 2",
"update person_pums set race = 3 where race1 >=3 and race1 <= 5",
"update person_pums set race = 4 where race1 = 6",
"update person_pums set race = 5 where race1 = 7",
"update person_pums set race = 6 where race1 = 8",
"update person_pums set race = 7 where race1 = 9",
"update person_pums set employment = 1 where esr = 0",
"update person_pums set employment = 2 where esr = 1 or esr = 2 or esr = 4 or esr = 5",
"update person_pums set employment = 3 where esr = 3",
"update person_pums set employment = 4 where esr = 6",
"alter table person_pums add index(serialno)",
"create table person_pums1 select person_pums.*, hhid from person_pums left join serialcorr using(serialno)",
"update person_pums1 set serialno = hhid",
"drop table person_sample",
"create table person_sample select state, pumano, hhid, serialno, pnum, agep, gender, race, employment, relate from person_pums1",
"alter table person_sample add index(serialno, pnum)",
"drop table hhld_sample_temp",
"alter table hhld_sample drop column hhldrage",
"alter table hhld_sample rename to hhld_sample_temp",
"drop table hhld_sample",
"create table hhld_sample select hhld_sample_temp.*, agep as hhldrage from hhld_sample_temp left join person_sample using(serialno) where relate = 0",
"alter table hhld_sample add index(serialno)",
"update hhld_sample set hhldrage = 1 where hhldrage <=7 ",
"update hhld_sample set hhldrage = 2 where hhldrage >7",
"drop table hhld_sample_temp",
"drop table person_pums1"]
DEFAULT_HOUSING_PUMS2000_QUERIES = ["alter table housing_pums add index(serialno)",
"alter table housing_pums add column hhtype bigint",
"alter table housing_pums add column hhldtype bigint",
"alter table housing_pums add column hhldinc bigint",
"alter table housing_pums add column hhldtenure bigint",
"alter table housing_pums add column hhldsize bigint",
"alter table housing_pums add column childpresence bigint",
"alter table housing_pums add column groupquarter bigint",
"alter table housing_pums add column hhldfam bigint",
"update housing_pums set hhtype = 1 where unittype = 0",
"update housing_pums set hhtype = 2 where unittype = 1 or unittype = 2",
"update housing_pums set hhldtype = 1 where hht = 1",
"update housing_pums set hhldtype = 2 where hht = 2",
"update housing_pums set hhldtype = 3 where hht = 3",
"update housing_pums set hhldtype = 4 where hht = 4 or hht = 5",
"update housing_pums set hhldtype = 5 where hht = 6 or hht = 7",
"update housing_pums set hhldtype = -99 where hht = 0",
"update housing_pums set hhldinc = 1 where hinc <15000",
"update housing_pums set hhldinc = 2 where hinc >= 15000 and hinc < 25000",
"update housing_pums set hhldinc = 3 where hinc >= 25000 and hinc < 35000",
"update housing_pums set hhldinc = 4 where hinc >= 35000 and hinc < 45000",
"update housing_pums set hhldinc = 5 where hinc >= 45000 and hinc < 60000",
"update housing_pums set hhldinc = 6 where hinc >= 60000 and hinc < 100000",
"update housing_pums set hhldinc = 7 where hinc >= 100000 and hinc < 150000",
"update housing_pums set hhldinc = 8 where hinc >= 150000",
"update housing_pums set hhldinc = -99 where hht = 0",
#"update housing_pums set hhldtenure = 1 where tenure = 1 or tenure = 2",
#"update housing_pums set hhldtenure = 2 where tenure = 3 or tenure = 4",
#"update housing_pums set hhldtenure = -99 where tenure = 0",
"update housing_pums set hhldsize = persons where persons < 7",
"update housing_pums set hhldsize = 7 where persons >= 7",
"update housing_pums set hhldsize = -99 where hht = 0",
"update housing_pums set childpresence = 1 where noc > 0",
"update housing_pums set childpresence = 2 where noc = 0",
"update housing_pums set childpresence = -99 where hht = 0",
"update housing_pums set groupquarter = unittype where unittype >0",
"update housing_pums set groupquarter = -99 where unittype =0",
"update housing_pums set hhldfam = 1 where hhldtype <=3",
"update housing_pums set hhldfam = 2 where hhldtype > 3",
"delete from housing_pums where persons = 0",
"drop table hhld_sample",
"drop table gq_sample",
"create table hhld_sample select state, pumano, hhid, serialno, hhtype, hhldtype, hhldinc, hhldsize, childpresence, hhldfam from housing_pums where hhtype = 1",
"create table gq_sample select state, pumano, hhid, serialno, hhtype, groupquarter from housing_pums where hhtype = 2",
"alter table hhld_sample add index(serialno)",
<|fim▁hole|> "alter table gq_sample add index(serialno)"]
DEFAULT_HOUSING_PUMSACS_QUERIES = ["alter table housing_pums add index(serialno)",
"alter table housing_pums change hincp hinc bigint",
"alter table housing_pums change np persons bigint",
"alter table housing_pums change hupaoc noc bigint",
"alter table housing_pums change type unittype bigint",
"alter table housing_pums change st state bigint",
"alter table housing_pums change puma pumano bigint",
"alter table housing_pums add column hhtype bigint",
"alter table housing_pums add column hhldtype bigint",
"alter table housing_pums add column hhldinc bigint",
"alter table housing_pums add column hhldtenure bigint",
"alter table housing_pums add column hhldsize bigint",
"alter table housing_pums add column childpresence bigint",
"alter table housing_pums add column groupquarter bigint",
"alter table housing_pums add column hhldfam bigint",
"update housing_pums set hhtype = 1 where unittype = 1",
"update housing_pums set hhtype = 2 where unittype = 2 or unittype = 3",
"update housing_pums set hhldtype = 1 where hht = 1",
"update housing_pums set hhldtype = 2 where hht = 2",
"update housing_pums set hhldtype = 3 where hht = 3",
"update housing_pums set hhldtype = 4 where hht = 4 or hht = 6",
"update housing_pums set hhldtype = 5 where hht = 5 or hht = 7",
"update housing_pums set hhldtype = -99 where hht = 0",
"update housing_pums set hhldinc = 1 where hinc <15000",
"update housing_pums set hhldinc = 2 where hinc >= 15000 and hinc < 25000",
"update housing_pums set hhldinc = 3 where hinc >= 25000 and hinc < 35000",
"update housing_pums set hhldinc = 4 where hinc >= 35000 and hinc < 45000",
"update housing_pums set hhldinc = 5 where hinc >= 45000 and hinc < 60000",
"update housing_pums set hhldinc = 6 where hinc >= 60000 and hinc < 100000",
"update housing_pums set hhldinc = 7 where hinc >= 100000 and hinc < 150000",
"update housing_pums set hhldinc = 8 where hinc >= 150000",
"update housing_pums set hhldinc = -99 where hht = 0",
#"update housing_pums set hhldtenure = 1 where tenure = 1 or tenure = 2",
#"update housing_pums set hhldtenure = 2 where tenure = 3 or tenure = 4",
#"update housing_pums set hhldtenure = -99 where tenure = 0",
"update housing_pums set hhldsize = persons where persons < 7",
"update housing_pums set hhldsize = 7 where persons >= 7",
"update housing_pums set hhldsize = -99 where hht = 0",
"update housing_pums set childpresence = 1 where noc =1 or noc = 2 or noc = 3",
"update housing_pums set childpresence = 2 where noc = 4",
"update housing_pums set childpresence = -99 where hht = 0",
"update housing_pums set groupquarter = 1 where unittype >1",
"update housing_pums set groupquarter = -99 where unittype =1",
"update housing_pums set hhldfam = 1 where hhldtype <=3",
"update housing_pums set hhldfam = 2 where hhldtype > 3",
"delete from housing_pums where persons = 0",
"drop table serialcorr",
"create table serialcorr select state, pumano, serialno from housing_pums group by serialno",
"alter table serialcorr add column hhid bigint primary key auto_increment not null",
"alter table serialcorr add index(serialno)",
"drop table hhld_sample",
"drop table gq_sample",
"alter table housing_pums add index(serialno)",
"create table housing_pums1 select housing_pums.*, hhid from housing_pums left join serialcorr using(serialno)",
"update housing_pums1 set serialno = hhid",
"create table hhld_sample select state, pumano, hhid, serialno, hhtype, hhldtype, hhldinc, hhldsize, childpresence, hhldfam from housing_pums1 where hhtype = 1",
"create table gq_sample select state, pumano, hhid, serialno, hhtype, groupquarter from housing_pums1 where hhtype = 2",
"alter table hhld_sample add index(serialno)",
"alter table gq_sample add index(serialno)",
"drop table housing_pums1"]
DEFAULT_SF2000_QUERIES = ["alter table %s add column agep1 bigint",
"alter table %s add column agep2 bigint",
"alter table %s add column agep3 bigint",
"alter table %s add column agep4 bigint",
"alter table %s add column agep5 bigint",
"alter table %s add column agep6 bigint",
"alter table %s add column agep7 bigint",
"alter table %s add column agep8 bigint",
"alter table %s add column agep9 bigint",
"alter table %s add column agep10 bigint",
"alter table %s add column gender1 bigint",
"alter table %s add column gender2 bigint",
"alter table %s add column race1 bigint",
"alter table %s add column race2 bigint",
"alter table %s add column race3 bigint",
"alter table %s add column race4 bigint",
"alter table %s add column race5 bigint",
"alter table %s add column race6 bigint",
"alter table %s add column race7 bigint",
"alter table %s add column employment1 bigint",
"alter table %s add column employment2 bigint",
"alter table %s add column employment3 bigint",
"alter table %s add column employment4 bigint",
"alter table %s add column childpresence1 bigint",
"alter table %s add column childpresence2 bigint",
"alter table %s add column groupquarter1 bigint",
"alter table %s add column groupquarter2 bigint",
"alter table %s add column hhldinc1 bigint",
"alter table %s add column hhldinc2 bigint",
"alter table %s add column hhldinc3 bigint",
"alter table %s add column hhldinc4 bigint",
"alter table %s add column hhldinc5 bigint",
"alter table %s add column hhldinc6 bigint",
"alter table %s add column hhldinc7 bigint",
"alter table %s add column hhldinc8 bigint",
"alter table %s add column hhldsize1 bigint",
"alter table %s add column hhldsize2 bigint",
"alter table %s add column hhldsize3 bigint",
"alter table %s add column hhldsize4 bigint",
"alter table %s add column hhldsize5 bigint",
"alter table %s add column hhldsize6 bigint",
"alter table %s add column hhldsize7 bigint",
"alter table %s add column hhldtype1 bigint",
"alter table %s add column hhldtype2 bigint",
"alter table %s add column hhldtype3 bigint",
"alter table %s add column hhldtype4 bigint",
"alter table %s add column hhldtype5 bigint",
"alter table %s add column hhldrage1 bigint",
"alter table %s add column hhldrage2 bigint",
"alter table %s add column hhldfam1 bigint",
"alter table %s add column hhldfam2 bigint",
"update %s set agep1 = (P008003+P008004+P008005+P008006+P008007) + (P008042+P008043+P008044+P008045+P008046)",
"update %s set agep2 = (P008008+P008009+P008010+P008011+P008012+P008013+P008014+P008015+P008016+P008017 ) + (P008047+P008048+P008049+P008050+P008051+P008052+P008053+P008054+P008055+P008056)",
"update %s set agep3 = (P008018+P008019+P008020+P008021+P008022+P008023+P008024+P008025 ) + (P008057+P008058+P008059+P008060+P008061+P008062+P008063+P008064)",
"update %s set agep4 = (P008026+P008027) + (P008065+P008066)",
"update %s set agep5 = (P008028+P008029) + (P008067+P008068)",
"update %s set agep6 = (P008030+P008031) + (P008069+P008070)",
"update %s set agep7 = (P008032+P008033+P008034) + (P008071+P008072+P008073)",
"update %s set agep8 = (P008035+P008036+P008037) + (P008074+P008075+P008076)",
"update %s set agep9 = (P008038+P008039) + (P008077+P008078)",
"update %s set agep10 = (P008040) + (P008079)",
"update %s set gender1 = P008002",
"update %s set gender2 = P008041",
"update %s set race1 = P006002",
"update %s set race2 = P006003",
"update %s set race3 = P006004",
"update %s set race4 = P006005",
"update %s set race5 = P006006",
"update %s set race6 = P006007",
"update %s set race7 = P006008",
"update %s set employment1 = agep1+agep2+P008018+P008057",
"update %s set employment2 = P043004+P043006+P043011+P043013",
"update %s set employment3 = P043007+P043014",
"update %s set employment4 = P043008+P043015",
"update %s set childpresence1 = P010008 + P010012 + P010015",
"update %s set childpresence2 = P010009 + P010013 + P010016 + P010017 + P010002",
"update %s set groupquarter1 = P009026",
"update %s set groupquarter2 = P009027",
"update %s set hhldinc1 = P052002 + P052003",
"update %s set hhldinc2 = P052004 + P052005",
"update %s set hhldinc3 = P052006 + P052007",
"update %s set hhldinc4 = P052008 + P052009",
"update %s set hhldinc5 = P052010 + P052011",
"update %s set hhldinc6 = P052012 + P052013",
"update %s set hhldinc7 = P052014 + P052015",
"update %s set hhldinc8 = P052016 + P052017",
"update %s set hhldsize1 = P014010 ",
"update %s set hhldsize2 = P014003+P014011 ",
"update %s set hhldsize3 = P014004+P014012 ",
"update %s set hhldsize4 = P014005+P014013 ",
"update %s set hhldsize5 = P014006+P014014 ",
"update %s set hhldsize6 = P014007+P014015 ",
"update %s set hhldsize7 = P014008+P014016 ",
"update %s set hhldtype1 = P010007",
"update %s set hhldtype2 = P010011 ",
"update %s set hhldtype3 = P010014",
"update %s set hhldtype4 = P010002",
"update %s set hhldtype5 = P010017",
"update %s set hhldrage1 = P012002",
"update %s set hhldrage2 = P012017",
"update %s set hhldfam1 = hhldtype1 + hhldtype2 + hhldtype3",
"update %s set hhldfam2 = hhldtype4 + hhldtype5",
"drop table hhld_marginals",
"drop table gq_marginals",
"drop table person_marginals",
"""create table hhld_marginals select state, county, tract, bg, hhldinc1, hhldinc2, hhldinc3, hhldinc4, hhldinc5, hhldinc6, hhldinc7, hhldinc8,"""
"""hhldsize1, hhldsize2, hhldsize3, hhldsize4, hhldsize5, hhldsize6, hhldsize7, hhldtype1, hhldtype2, hhldtype3, hhldtype4, hhldtype5,"""
"""childpresence1, childpresence2, hhldrage1, hhldrage2, hhldfam1, hhldfam2 from %s""",
"create table gq_marginals select state, county, tract, bg, groupquarter1, groupquarter2 from %s",
"""create table person_marginals select state, county, tract, bg, agep1, agep2, agep3, agep4, agep5, agep6, agep7, agep8, agep9, agep10,"""
"""gender1, gender2, race1, race2, race3, race4, race5, race6, race7, employment1, employment2, employment3, employment4 from"""
""" %s"""]
DEFAULT_SFACS_QUERIES = ["alter table %s add column agep1 bigint",
"alter table %s add column agep2 bigint",
"alter table %s add column agep3 bigint",
"alter table %s add column agep4 bigint",
"alter table %s add column agep5 bigint",
"alter table %s add column agep6 bigint",
"alter table %s add column agep7 bigint",
"alter table %s add column agep8 bigint",
"alter table %s add column agep9 bigint",
"alter table %s add column agep10 bigint",
"alter table %s add column gender1 bigint",
"alter table %s add column gender2 bigint",
"alter table %s add column race1 bigint",
"alter table %s add column race2 bigint",
"alter table %s add column race3 bigint",
"alter table %s add column race4 bigint",
"alter table %s add column race5 bigint",
"alter table %s add column race6 bigint",
"alter table %s add column race7 bigint",
"alter table %s add column race11 bigint",
"alter table %s add column race12 bigint",
"alter table %s add column race13 bigint",
"alter table %s add column race14 bigint",
"alter table %s add column race15 bigint",
"alter table %s add column race16 bigint",
"alter table %s add column race17 bigint",
"alter table %s add column race21 bigint",
"alter table %s add column race22 bigint",
"alter table %s add column race23 bigint",
"alter table %s add column race24 bigint",
"alter table %s add column race25 bigint",
"alter table %s add column race26 bigint",
"alter table %s add column race27 bigint",
"alter table %s add column employment1 bigint",
"alter table %s add column employment2 bigint",
"alter table %s add column employment3 bigint",
"alter table %s add column employment4 bigint",
"alter table %s add column childpresence1 bigint",
"alter table %s add column childpresence2 bigint",
"alter table %s add column groupquarter1 bigint",
"alter table %s add column hhldinc1 bigint",
"alter table %s add column hhldinc2 bigint",
"alter table %s add column hhldinc3 bigint",
"alter table %s add column hhldinc4 bigint",
"alter table %s add column hhldinc5 bigint",
"alter table %s add column hhldinc6 bigint",
"alter table %s add column hhldinc7 bigint",
"alter table %s add column hhldinc8 bigint",
"alter table %s add column hhldsize1 bigint",
"alter table %s add column hhldsize2 bigint",
"alter table %s add column hhldsize3 bigint",
"alter table %s add column hhldsize4 bigint",
"alter table %s add column hhldsize5 bigint",
"alter table %s add column hhldsize6 bigint",
"alter table %s add column hhldsize7 bigint",
"alter table %s add column hhldtype1 bigint",
"alter table %s add column hhldtype2 bigint",
"alter table %s add column hhldtype3 bigint",
"alter table %s add column hhldtype4 bigint",
"alter table %s add column hhldtype5 bigint",
"alter table %s add column hhldrage1 bigint",
"alter table %s add column hhldrage2 bigint",
"alter table %s add column hhldfam1 bigint",
"alter table %s add column hhldfam2 bigint",
"alter table %s add column check_gender bigint",
"alter table %s add column check_age bigint",
"alter table %s add column check_race bigint",
"alter table %s add column check_race1 bigint",
"alter table %s add column check_race2 bigint",
"alter table %s add column check_employment bigint",
"alter table %s add column check_type bigint",
"alter table %s add column check_size bigint",
"alter table %s add column check_fam bigint",
"alter table %s add column check_hhldrage bigint",
"alter table %s add column check_inc bigint",
"alter table %s add column check_child bigint",
"update %s set agep1 = (B01001000003)+(B01001000027)",
"update %s set agep2 = (B01001000004+B01001000005) + (B01001000028+B01001000029)",
"update %s set agep3 = (B01001000006+B01001000007+B01001000008+B01001000009+B01001000010) + (B01001000030+B01001000031+B01001000032+B01001000033+B01001000034)",
"update %s set agep4 = (B01001000011+B01001000012) + (B01001000035+B01001000036)",
"update %s set agep5 = (B01001000013+B01001000014) + (B01001000037+B01001000038)",
"update %s set agep6 = (B01001000015+B01001000016) + (B01001000039+B01001000040)",
"update %s set agep7 = (B01001000017+B01001000018+B01001000019) + (B01001000041+B01001000042+B01001000043)",
"update %s set agep8 = (B01001000020+B01001000021+B01001000022) + (B01001000044+B01001000045+B01001000046)",
"update %s set agep9 = (B01001000023+B01001000024) + (B01001000047+B01001000048)",
"update %s set agep10 = (B01001000025) + (B01001000049)",
"update %s set gender1 = B01001000002",
"update %s set gender2 = B01001000026",
"update %s set race1 = B02001000002",
"update %s set race2 = B02001000003",
"update %s set race3 = B02001000004",
"update %s set race4 = B02001000005",
"update %s set race5 = B02001000006",
"update %s set race6 = B02001000007",
"update %s set race7 = B02001000009+B02001000010",
"update %s set race11 = C01001A00001",
"update %s set race12 = C01001B00001",
"update %s set race13 = C01001C00001",
"update %s set race14 = C01001D00001",
"update %s set race15 = C01001E00001",
"update %s set race16 = C01001F00001",
"update %s set race17 = C01001G00001",
"update %s set race21 = B01001A00001",
"update %s set race22 = B01001B00001",
"update %s set race23 = B01001C00001",
"update %s set race24 = B01001D00001",
"update %s set race25 = B01001E00001",
"update %s set race26 = B01001F00001",
"update %s set race27 = B01001G00001",
"""update %s set employment2 = (B23001000005 + B23001000007) + (B23001000012 + B23001000014) + """
"""(B23001000019 + B23001000021) + (B23001000026 + B23001000028) + (B23001000033 + B23001000035) + """
"""(B23001000040 + B23001000042) + (B23001000047 + B23001000049) + (B23001000054 + B23001000056) + """
"""(B23001000061 + B23001000063) + (B23001000068 + B23001000070) + (B23001000075 + B23001000080 + B23001000085) + """
"""(B23001000091 + B23001000093) + (B23001000098 + B23001000100) + """
"""(B23001000105 + B23001000107) + (B23001000112 + B23001000114) + (B23001000119 + B23001000121) + """
"""(B23001000126 + B23001000128) + (B23001000133 + B23001000135) + (B23001000140 + B23001000142) + """
"""(B23001000147 + B23001000149) + (B23001000154 + B23001000156) + (B23001000161 + B23001000166 + B23001000171)""",
"""update %s set employment3 = (B23001000008 + B23001000015 + B23001000022 + """
"""B23001000029 + B23001000036 + B23001000043 + B23001000050 + B23001000057 + B23001000064 +"""
"""B23001000071 + B23001000076 + B23001000081 + B23001000086 + B23001000094 + B23001000101 +"""
"""B23001000108 + B23001000115 + B23001000122 + B23001000129 + B23001000136 + B23001000143 +"""
"""B23001000150 + B23001000157 + B23001000162 + B23001000167 + B23001000172) """,
"""update %s set employment4 = (B23001000009 + B23001000016 + B23001000023 + """
"""B23001000030 + B23001000037 + B23001000044 + B23001000051 + B23001000058 + B23001000065 +"""
"""B23001000072 + B23001000077 + B23001000082 + B23001000087 + B23001000095 + B23001000102 +"""
"""B23001000109 + B23001000116 + B23001000123 + B23001000130 + B23001000137 + B23001000144 +"""
"""B23001000151 + B23001000158 + B23001000163 + B23001000168 + B23001000173) """,
"update %s set employment1 = gender1 + gender2 - employment2 - employment3 - employment4",
"update %s set groupquarter1 = B26001000001",
"update %s set hhldinc1 = B19001000002 + B19001000003",
"update %s set hhldinc2 = B19001000004 + B19001000005",
"update %s set hhldinc3 = B19001000006 + B19001000007",
"update %s set hhldinc4 = B19001000008 + B19001000009",
"update %s set hhldinc5 = B19001000010 + B19001000011",
"update %s set hhldinc6 = B19001000012 + B19001000013",
"update %s set hhldinc7 = B19001000014 + B19001000015",
"update %s set hhldinc8 = B19001000016 + B19001000017",
"update %s set hhldsize1 = B25009000003+B25009000011",
"update %s set hhldsize2 = B25009000004+B25009000012",
"update %s set hhldsize3 = B25009000005+B25009000013",
"update %s set hhldsize4 = B25009000006+B25009000014",
"update %s set hhldsize5 = B25009000007+B25009000015",
"update %s set hhldsize6 = B25009000008+B25009000016",
"update %s set hhldsize7 = B25009000009+B25009000017",
"update %s set hhldtype1 = B11001000003",
"update %s set hhldtype2 = B11001000005",
"update %s set hhldtype3 = B11001000006",
"update %s set hhldtype4 = B11001000008",
"update %s set hhldtype5 = B11001000009",
"""update %s set hhldrage1 = (B25007000003+B25007000004+B25007000005+B25007000006+B25007000007+B25007000008)+"""
"""(B25007000013+B25007000014+B25007000015+B25007000016+B25007000017+B25007000018)""",
"update %s set hhldrage2 = (B25007000009+ B25007000010+B25007000011)+(B25007000019+ B25007000020+B25007000021)",
"update %s set hhldfam1 = hhldtype1 + hhldtype2 + hhldtype3",
"update %s set hhldfam2 = hhldtype4 + hhldtype5",
"update %s set childpresence1 = C23007000002",
"update %s set childpresence2 = C23007000017 + hhldtype4 + hhldtype5",
"update %s set check_gender = gender1 + gender2",
"update %s set check_age = agep1+agep2+agep3+agep4+agep5+agep6+agep7+agep8+agep9+agep10",
"update %s set check_race = race1+race2+race3+race4+race5+race6+race7",
"update %s set check_race1 = race11+race12+race13+race14+race15+race16+race17",
"update %s set check_race2 = race21+race22+race23+race24+race25+race26+race27",
"update %s set check_employment = employment1 + employment2 + employment3 + employment4",
"update %s set check_type = hhldtype1+hhldtype2+hhldtype3+hhldtype4+hhldtype5",
"update %s set check_size = hhldsize1+hhldsize2+hhldsize3+hhldsize4+hhldsize5+hhldsize6+hhldsize7",
"update %s set check_hhldrage = hhldrage1+hhldrage2",
"update %s set check_inc = hhldinc1+hhldinc2+hhldinc3+hhldinc4+hhldinc5+hhldinc6+hhldinc7+hhldinc8",
"update %s set check_fam = hhldfam1+hhldfam2",
"update %s set check_child = childpresence1+childpresence2",
"drop table hhld_marginals",
"drop table gq_marginals",
"drop table person_marginals",
"""create table hhld_marginals select state, county, tract, bg, hhldinc1, hhldinc2, hhldinc3, hhldinc4, hhldinc5, hhldinc6, hhldinc7, hhldinc8,"""
"""hhldsize1, hhldsize2, hhldsize3, hhldsize4, hhldsize5, hhldsize6, hhldsize7, hhldtype1, hhldtype2, hhldtype3, hhldtype4, hhldtype5,"""
"""childpresence1, childpresence2, hhldrage1, hhldrage2, hhldfam1, hhldfam2 from %s""",
"create table gq_marginals select state, county, tract, bg, groupquarter1 from %s",
"""create table person_marginals select state, county, tract, bg, agep1, agep2, agep3, agep4, agep5, agep6, agep7, agep8, agep9, agep10,"""
"""gender1, gender2, race1, race2, race3, race4, race5, race6, race7 from %s"""]<|fim▁end|> | |
<|file_name|>client.py<|end_file_name|><|fim▁begin|><|fim▁hole|> def __init__(self, mac):
self.__mac__ = mac
def hub(self, hub):
return Hub(self.__mac__, hub)<|fim▁end|> | from .hub import Hub
class Client(object): |
<|file_name|>Lowest_Common_Ancestor.py<|end_file_name|><|fim▁begin|># Find the Lowest Common Ancestor (LCA) in a Binary Search Tree
# A Binary Search Tree node
class Node:
# Constructor to initialise node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert_node(self, data):
if self.root is None:
self.root = Node(data)
else:
self._insert(data, self.root)
def _insert(self, data, current_node):
if data <= current_node.data:
if current_node.left is not None:
self._insert(data, current_node.left)
else:
current_node.left = Node(data)
else:
if current_node.right is not None:
self._insert(data, current_node.right)
else:
current_node.right = Node(data)
def inorder(self):
current_node = self.root
self._inorder(current_node)
print('End')
def _inorder(self, current_node):
if current_node is None:
return
self._inorder(current_node.left)
print(current_node.data, " -> ", end='')
self._inorder(current_node.right)
# assuming both nodes are present in the tree
def lca_bst(root, value1, value2):
while root is not None:
if value2 > root.data < value1:
root = root.right
elif value2 < root.data > value1:
root = root.left
else:
return root.data
<|fim▁hole|>
if __name__ == '__main__':
tree = BST()
tree.insert_node(6)
tree.insert_node(8)
tree.insert_node(9)
tree.insert_node(6)
tree.insert_node(5)
tree.insert_node(7)
tree.insert_node(3)
tree.insert_node(2)
tree.insert_node(4)
print(lca_bst(tree.root, 4, 2))
"""
given tree:
6
6 8
5 7 9
3
2 4
"""<|fim▁end|> | |
<|file_name|>test.js<|end_file_name|><|fim▁begin|>/* global require, describe, it */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Matrix data structure:
matrix = require( 'dstructs-matrix' ),
// Validate a value is NaN:
isnan = require( 'validate.io-nan' ),
// Cast typed arrays to a different data type
cast = require( 'compute-cast-arrays' ),
// Module to be tested:
ceil = require( './../lib' ),
// Floor function:
CEIL = require( './../lib/number.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'compute-ceil', function tests() {
it( 'should export a function', function test() {
expect( ceil ).to.be.a( 'function' );
});
it( 'should throw an error if provided an invalid option', function test() {
var values = [
'5',
5,
true,
undefined,
null,
NaN,
[],
{}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
ceil( [1,2,3], {
'accessor': value
});
};
}
});
it( 'should throw an error if provided an array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
ceil( [1,2,3], {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a typed-array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
ceil( new Int8Array([1,2,3]), {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a matrix and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
ceil( matrix( [2,2] ), {
'dtype': value
});
};
}
});
it( 'should return NaN if the first argument is neither a number, array-like, or matrix-like', function test() {
var values = [
// '5', // valid as is array-like (length)
true,
undefined,
null,
// NaN, // allowed
function(){},
{}
];
for ( var i = 0; i < values.length; i++ ) {
assert.isTrue( isnan( ceil( values[ i ] ) ) );
}
});
it( 'should compute the ceil function when provided a number', function test() {
assert.strictEqual( ceil( 0.4 ), 1 );
assert.strictEqual( ceil( 1.8 ), 2 );
assert.isTrue( isnan( ceil( NaN ) ) );
});
it( 'should evaluate the ceil function when provided a plain array', function test() {
var data, actual, expected;
data = [
-9.4,
-4.1,
-2.9,
-0.5,
0,
0.3,
2,
3.9,
4.2,
5.1
];
expected = [
-9,
-4,
-2,
-0,
0,
1,
2,
4,
5,
6
];
actual = ceil( data );
assert.notEqual( actual, data );
assert.deepEqual( actual, expected );
// Mutate...
actual = ceil( data, {
'copy': false
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function when provided a typed array', function test() {
var data, actual, expected;
data = new Float32Array([
-9.4,
-4.1,
-2.9,
-0.5,
0,
0.3,
2,
3.9,
4.2,
5.1
]);
expected = new Int32Array([
-9,
-4,
-2,
-0,
0,
1,
2,
4,
5,
6
]);
actual = ceil( data );
assert.notEqual( actual, data );
assert.deepEqual( actual, expected );
// Mutate:
actual = ceil( data, {
'copy': false
});
expected = new Float32Array([
-9,
-4,
-2,
-0,
0,
1,
2,
4,
5,
6
]);
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function element-wise and return an array of a specific type', function test() {
var data, actual, expected;
data = [ -3.3, -2, -1.3, 0, 1.3, 2.9, 3.3 ];
expected = new Int8Array( [ -3, -2, -1, 0, 2, 3, 4 ] );
actual = ceil( data, {
'dtype': 'int8'
});
assert.notEqual( actual, data );
assert.strictEqual( actual.BYTES_PER_ELEMENT, 1 );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function element-wise using an accessor', function test() {
var data, actual, expected;
data = [
[1,1e-306],
[2,-1e-306],
[3,1e-299],
[4,-1e-299],
[5,0.8],
[6,-0.8],
[7,1],
[8,-1],
[9,10.9],
[10,-10],
[11,2.4],
[12,-2.1],
[13,3.2],
[14,-3]
];
expected = [
1,
-0,
1,
-0,
1,
-0,
1,
-1,
11,
-10,
3,
-2,
4,
-3
];
actual = ceil( data, {
'accessor': getValue
});
assert.notEqual( actual, data );
assert.deepEqual( actual, expected );
// Mutate:
actual = ceil( data, {
'accessor': getValue,
'copy': false
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
function getValue( d ) {
return d[ 1 ];
}
});
it( 'should evaluate the ceil function element-wise and deep set', function test() {
var data, actual, expected;
data = [
{'x':[9,-9.4]},
{'x':[9,-4.1]},
{'x':[9,-2.9]},
{'x':[9,-0.5]},
{'x':[9,0]},
{'x':[9,0.3]},
{'x':[9,2]},
{'x':[9,3.9]},
{'x':[9,4.2]},
{'x':[9,5.1]}
];
expected = [
{'x':[9,-9]},
{'x':[9,-4]},
{'x':[9,-2]},
{'x':[9,-0]},
{'x':[9,0]},
{'x':[9,1]},
{'x':[9,2]},
{'x':[9,4]},
{'x':[9,5]},
{'x':[9,6]}
];
actual = ceil( data, {
'path': 'x.1'
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
// Specify a path with a custom separator...
data = [
{'x':[9,-9.4]},
{'x':[9,-4.1]},
{'x':[9,-2.9]},
{'x':[9,-0.5]},
{'x':[9,0]},
{'x':[9,0.3]},
{'x':[9,2]},
{'x':[9,3.9]},
{'x':[9,4.2]},
{'x':[9,5.1]}
];
actual = ceil( data, {
'path': 'x/1',
'sep': '/'
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function element-wise when provided a matrix', function test() {
var mat,
out,
d1,
d2,
i;
d1 = new Float64Array( 25 );
d2 = new Int32Array( 25 );
for ( i = 0; i < d1.length; i++ ) {<|fim▁hole|> d1[ i ] = i / 5;
d2[ i ] = CEIL( i / 5 );
}
mat = matrix( d1, [5,5], 'float64' );
out = ceil( mat );
assert.deepEqual( out.data, d2 );
// Mutate...
out = ceil( mat, {
'copy': false
});
assert.strictEqual( mat, out );
assert.deepEqual( mat.data, cast( d2, 'float64') );
});
it( 'should evaluate the ceil function element-wise and return a matrix of a specific type', function test() {
var mat,
out,
d1,
d2,
i;
d1 = new Float64Array( 25 );
d2 = new Float32Array( 25 );
for ( i = 0; i < d1.length; i++ ) {
d1[ i ] = i / 5;
d2[ i ] = CEIL( i / 5 );
}
mat = matrix( d1, [5,5], 'float64' );
out = ceil( mat, {
'dtype': 'float32'
});
assert.strictEqual( out.dtype, 'float32' );
assert.deepEqual( out.data, d2 );
});
it( 'should return an empty data structure if provided an empty data structure', function test() {
assert.deepEqual( ceil( [] ), [] );
assert.deepEqual( ceil( matrix( [0,0] ) ).data, new Int32Array() );
assert.deepEqual( ceil( new Int8Array() ), new Int32Array() );
});
});<|fim▁end|> | |
<|file_name|>test_jvm_app.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from builtins import str
from textwrap import dedent
from pants.backend.jvm.targets.jvm_app import JvmApp
from pants.backend.jvm.targets.jvm_binary import JvmBinary
from pants.base.exceptions import TargetDefinitionException
from pants.base.parse_context import ParseContext
from pants.build_graph.address import Address
from pants.build_graph.app_base import Bundle, DirectoryReMapper
from pants.source.wrapped_globs import Globs
from pants_test.test_base import TestBase
def _bundle(rel_path):
pc = ParseContext(rel_path=rel_path, type_aliases={})
return Bundle(pc)
def _globs(rel_path):
pc = ParseContext(rel_path=rel_path, type_aliases={})
return Globs(pc)
class JvmAppTest(TestBase):
def test_simple(self):
binary_target = self.make_target(':foo-binary', JvmBinary, main='com.example.Foo')
app_target = self.make_target(':foo', JvmApp, basename='foo-app', binary=':foo-binary')
self.assertEqual('foo-app', app_target.payload.basename)
self.assertEqual('foo-app', app_target.basename)
self.assertEqual(binary_target, app_target.binary)
self.assertEqual([':foo-binary'], list(app_target.compute_dependency_specs(payload=app_target.payload)))
def test_jvmapp_bundle_payload_fields(self):
app_target = self.make_target(':foo_payload',
JvmApp,
basename='foo-payload-app',
archive='zip')
self.assertEqual('foo-payload-app', app_target.payload.basename)
self.assertIsNone(app_target.payload.deployjar)
self.assertEqual('zip', app_target.payload.archive)
def test_bad_basename(self):
with self.assertRaisesRegexp(TargetDefinitionException,
r'Invalid target JvmApp.* basename must not equal name.'):
self.make_target(':foo', JvmApp, basename='foo')
def create_app(self, rel_path, name=None, **kwargs):
self.create_file(os.path.join(rel_path, 'config/densities.xml'))
return self.make_target(Address(rel_path, name or 'app').spec,
JvmApp,
bundles=[_bundle(rel_path)(fileset='config/densities.xml')],
**kwargs)
def test_binary_via_binary(self):
bin = self.make_target('src/java/org/archimedes/buoyancy:bin', JvmBinary)
app = self.create_app('src/java/org/archimedes/buoyancy', binary=':bin')
self.assertEqual(app.binary, bin)
def test_binary_via_dependencies(self):
bin = self.make_target('src/java/org/archimedes/buoyancy:bin', JvmBinary)
app = self.create_app('src/java/org/archimedes/buoyancy', dependencies=[bin])
self.assertEqual(app.binary, bin)
def test_degenerate_binaries(self):
bin = self.make_target('src/java/org/archimedes/buoyancy:bin', JvmBinary)
app = self.create_app('src/java/org/archimedes/buoyancy', binary=':bin', dependencies=[bin])
self.assertEqual(app.binary, bin)
def test_no_binary(self):
app = self.create_app('src/java/org/archimedes/buoyancy')
with self.assertRaisesRegexp(TargetDefinitionException,
r'Invalid target JvmApp.*src/java/org/archimedes/buoyancy:app\).*'
r' An app must define exactly one'):
app.binary
def test_too_many_binaries_mixed(self):
self.make_target('src/java/org/archimedes/buoyancy:bin', JvmBinary)
bin2 = self.make_target('src/java/org/archimedes/buoyancy:bin2', JvmBinary)
app = self.create_app('src/java/org/archimedes/buoyancy', binary=':bin', dependencies=[bin2])
with self.assertRaisesRegexp(TargetDefinitionException,
r'Invalid target JvmApp.*src/java/org/archimedes/buoyancy:app\).*'
r' An app must define exactly one'):
app.binary
def test_too_many_binaries_via_deps(self):
bin = self.make_target('src/java/org/archimedes/buoyancy:bin', JvmBinary)
bin2 = self.make_target('src/java/org/archimedes/buoyancy:bin2', JvmBinary)
app = self.create_app('src/java/org/archimedes/buoyancy', dependencies=[bin, bin2])
with self.assertRaisesRegexp(TargetDefinitionException,
r'Invalid target JvmApp.*src/java/org/archimedes/buoyancy:app\).*'
r' An app must define exactly one'):
app.binary
def test_not_a_binary(self):
self.make_target('src/java/org/archimedes/buoyancy:bin', JvmBinary)
self.create_app('src/java/org/archimedes/buoyancy', name='app', binary=':bin')
app = self.create_app('src/java/org/archimedes/buoyancy', name='app2', binary=':app')
with self.assertRaisesRegexp(TargetDefinitionException,
r'Invalid target JvmApp.*src/java/org/archimedes/buoyancy:app2\).*'
r' Expected binary dependency'):
app.binary
class BundleTest(TestBase):
def test_bundle_filemap_dest_bypath(self):
spec_path = 'src/java/org/archimedes/buoyancy'
densities = self.create_file(os.path.join(spec_path, 'config/densities.xml'))
unused = self.make_target(Address(spec_path, 'unused').spec, JvmBinary)
app = self.make_target(spec_path,
JvmApp,
dependencies=[unused],
bundles=[_bundle(spec_path)(fileset='config/densities.xml')])
self.assertEqual(1, len(app.bundles))
# after one big refactor, ../../../../../ snuck into this path:
self.assertEqual({densities: 'config/densities.xml'}, app.bundles[0].filemap)<|fim▁hole|> spec_path = 'src/java/org/archimedes/tub'
one = self.create_file(os.path.join(spec_path, 'config/one.xml'))
two = self.create_file(os.path.join(spec_path, 'config/two.xml'))
unused = self.make_target(Address(spec_path, 'unused').spec, JvmBinary)
globs = _globs(spec_path)
app = self.make_target(spec_path,
JvmApp,
dependencies=[unused],
bundles=[_bundle(spec_path)(fileset=globs('config/*.xml'))])
self.assertEqual(1, len(app.bundles))
self.assertEqual({one: 'config/one.xml', two: 'config/two.xml'}, app.bundles[0].filemap)
def test_bundle_filemap_dest_relative(self):
spec_path = 'src/java/org/archimedes/crown'
five = self.create_file(os.path.join(spec_path, 'gold/config/five.xml'))
unused = self.make_target(Address(spec_path, 'unused').spec, JvmBinary)
app = self.make_target(spec_path,
JvmApp,
dependencies=[unused],
bundles=[_bundle(spec_path)(relative_to='gold',
fileset='gold/config/five.xml')])
self.assertEqual(1, len(app.bundles))
self.assertEqual({five: 'config/five.xml'}, app.bundles[0].filemap)
def test_bundle_filemap_dest_remap(self):
spec_path = 'src/java/org/archimedes/crown'
one = self.create_file(os.path.join(spec_path, 'config/one.xml'))
unused = self.make_target(Address(spec_path, 'unused').spec, JvmBinary)
mapper = DirectoryReMapper(os.path.join(spec_path, 'config'), 'gold/config')
app = self.make_target(spec_path,
JvmApp,
dependencies=[unused],
bundles=[_bundle(spec_path)(mapper=mapper, fileset='config/one.xml')])
self.assertEqual(1, len(app.bundles))
self.assertEqual({one: 'gold/config/one.xml'}, app.bundles[0].filemap)
def test_bundle_filemap_remap_base_not_exists(self):
# Create directly
with self.assertRaises(DirectoryReMapper.NonexistentBaseError):
DirectoryReMapper("dummy/src/java/org/archimedes/crown/missing", "dummy")
def test_bundle_add(self):
spec_path = 'src/java/org/archimedes/volume'
stone_dense = self.create_file(os.path.join(spec_path, 'config/stone/dense.xml'))
metal_dense = self.create_file(os.path.join(spec_path, 'config/metal/dense.xml'))
unused = self.make_target(Address(spec_path, 'unused').spec, JvmBinary)
bundle = _bundle(spec_path)(relative_to='config',
fileset=['config/stone/dense.xml', 'config/metal/dense.xml'])
app = self.make_target(spec_path, JvmApp, dependencies=[unused], bundles=[bundle])
self.assertEqual(1, len(app.bundles))
self.assertEqual({stone_dense: 'stone/dense.xml', metal_dense: 'metal/dense.xml'},
app.bundles[0].filemap)
def test_multiple_bundles(self):
spec_path = 'src/java/org/archimedes/volume'
stone_dense = self.create_file(os.path.join(spec_path, 'config/stone/dense.xml'))
metal_dense = self.create_file(os.path.join(spec_path, 'config/metal/dense.xml'))
unused = self.make_target(Address(spec_path, 'unused').spec, JvmBinary)
self.add_to_build_file('src/java/org/archimedes/volume/BUILD', dedent("""
jvm_app(name='volume',
dependencies=[':unused'],
bundles=[
bundle(relative_to='config', fileset='config/stone/dense.xml')
]
)
jvm_app(name='bathtub',
dependencies=[':unused'],
bundles=[
bundle(fileset='config/metal/dense.xml')
]
)
"""))
app1 = self.make_target(Address(spec_path, 'app1').spec,
JvmApp,
dependencies=[unused],
bundles=[_bundle(spec_path)(relative_to='config',
fileset='config/stone/dense.xml')])
app2 = self.make_target(Address(spec_path, 'app2').spec,
JvmApp,
dependencies=[unused],
bundles=[_bundle(spec_path)(fileset='config/metal/dense.xml')])
self.assertEqual(1, len(app1.bundles))
self.assertEqual({stone_dense: 'stone/dense.xml'}, app1.bundles[0].filemap)
self.assertEqual(1, len(app2.bundles))
self.assertEqual({metal_dense: 'config/metal/dense.xml'}, app2.bundles[0].filemap)
def test_globs_relative_to_build_root(self):
spec_path = 'y'
unused = self.make_target(spec_path, JvmBinary)
globs = _globs(spec_path)
app = self.make_target('y:app',
JvmApp,
dependencies=[unused],
bundles=[
_bundle(spec_path)(fileset=globs("z/*")),
_bundle(spec_path)(fileset=['a/b'])
])
self.assertEqual(['y/a/b', 'y/z/*'], sorted(app.globs_relative_to_buildroot()['globs']))
def test_list_of_globs_fails(self):
# It's not allowed according to the docs, and will behave badly.
spec_path = 'y'
globs = _globs(spec_path)
with self.assertRaises(ValueError):
_bundle(spec_path)(fileset=[globs("z/*")])
def test_jvmapp_fingerprinting(self):
spec_path = 'y'
globs = _globs(spec_path)
self.create_file(os.path.join(spec_path, 'one.xml'))
self.create_file(os.path.join(spec_path, 'config/two.xml'))
def calc_fingerprint():
# Globs are eagerly, therefore we need to recreate target to recalculate fingerprint.
self.reset_build_graph()
app = self.make_target('y:app',
JvmApp,
dependencies=[],
bundles=[
_bundle(spec_path)(fileset=globs("*"))
])
return app.payload.fingerprint()
fingerprint_before = calc_fingerprint()
os.mkdir(os.path.join(self.build_root, spec_path, 'folder_one'))
self.assertEqual(fingerprint_before, calc_fingerprint())
self.create_file(os.path.join(spec_path, 'three.xml'))
self.assertNotEqual(fingerprint_before, calc_fingerprint())
def test_jvmapp_fingerprinting_with_non_existing_files(self):
spec_path = 'y'
def calc_fingerprint():
self.reset_build_graph()
return self.make_target('y:app',
JvmApp,
dependencies=[],
bundles=[
_bundle(spec_path)(fileset=['one.xml'])
]).payload.fingerprint()
fingerprint_non_existing_file = calc_fingerprint()
self.create_file(os.path.join(spec_path, 'one.xml'))
fingerprint_empty_file = calc_fingerprint()
self.create_file(os.path.join(spec_path, 'one.xml'), contents='some content')
fingerprint_file_with_content = calc_fingerprint()
self.assertNotEqual(fingerprint_empty_file, fingerprint_non_existing_file)
self.assertNotEqual(fingerprint_empty_file, fingerprint_file_with_content)
self.assertNotEqual(fingerprint_file_with_content, fingerprint_empty_file)
def test_rel_path_with_glob_fails(self):
# Globs are treated as eager, so rel_path doesn't affect their meaning.
# The effect of this is likely to be confusing, so disallow it.
spec_path = 'y'
self.create_file(os.path.join(spec_path, 'z', 'somefile'))
globs = _globs(spec_path)
with self.assertRaises(ValueError) as cm:
_bundle(spec_path)(rel_path="config", fileset=globs('z/*'))
self.assertIn("Must not use a glob for 'fileset' with 'rel_path'.", str(cm.exception))
def test_allow_globs_when_rel_root_matches_rel_path(self):
# If a glob has the same rel_root as the rel_path, then
# it will correctly pick up the right files.
# We don't allow BUILD files to have declarations with this state.
# But filesets can be created this way via macros or pants internals.
self.create_file(os.path.join('y', 'z', 'somefile'))
bundle = _bundle('y')(rel_path="y/z", fileset=_globs('y/z')('*'))
self.assertEqual({'globs': [u'y/z/*']}, bundle.fileset.filespec)
def test_rel_path_overrides_context_rel_path_for_explicit_path(self):
spec_path = 'y'
unused = self.make_target(spec_path, JvmBinary)
app = self.make_target('y:app',
JvmApp,
dependencies=[unused],
bundles=[
_bundle(spec_path)(rel_path="config", fileset=['a/b'])
])
self.assertEqual({os.path.join(self.build_root, 'config/a/b'): 'a/b'}, app.bundles[0].filemap)
self.assertEqual(['config/a/b'], sorted(app.globs_relative_to_buildroot()['globs']))<|fim▁end|> |
def test_bundle_filemap_dest_byglobs(self): |
<|file_name|>liveness-issue-2163.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|> let a: ~[int] = ~[];
vec::each(a, |_| -> bool {
//~^ ERROR mismatched types
});
}<|fim▁end|> | fn main() { |
<|file_name|>Tax_Card.java<|end_file_name|><|fim▁begin|>/**
*/
package TaxationWithRoot;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Tax Card</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link TaxationWithRoot.Tax_Card#getCard_identifier <em>Card identifier</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getTax_office <em>Tax office</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getPercentage_of_witholding <em>Percentage of witholding</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getTax_payers_name_surname <em>Tax payers name surname</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getTax_payers_partner_name_surname <em>Tax payers partner name surname</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getTax_payers_address <em>Tax payers address</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getJobs_Employer_SSNo <em>Jobs Employer SS No</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getJobs_employers_name <em>Jobs employers name</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getJobs_activity_type <em>Jobs activity type</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getJobs_place_of_work <em>Jobs place of work</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FD_daily <em>Deduction FD daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FD_monthly <em>Deduction FD monthly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_AC_daily <em>Deduction AC daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_AC_monthly <em>Deduction AC monthly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_AC_yearly <em>Deduction AC yearly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_CE_daily <em>Deduction CE daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_CE_monthly <em>Deduction CE monthly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_CE_yearly <em>Deduction CE yearly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_daily <em>Deduction DS daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_monthly <em>Deduction DS monthly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FO_daily <em>Deduction FO daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FO_monthly <em>Deduction FO monthly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FO_yearly <em>Deduction FO yearly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIS_daily <em>Credit CIS daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIS_monthly <em>Credit CIS monthly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIM_daily <em>Credit CIM daily</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#isValidity <em>Validity</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getIncome_Tax_Credit <em>Income Tax Credit</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getPrevious <em>Previous</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getCurrent_tax_card <em>Current tax card</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIM_yearly <em>Credit CIM yearly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Alimony_yearly <em>Deduction DS Alimony yearly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Debt_yearly <em>Deduction DS Debt yearly</em>}</li>
* <li>{@link TaxationWithRoot.Tax_Card#getIncome <em>Income</em>}</li>
* </ul>
*
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card()
* @model
* @generated
*/
public interface Tax_Card extends EObject {
/**
* Returns the value of the '<em><b>Card identifier</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Card identifier</em>' attribute.
* @see #setCard_identifier(String)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Card_identifier()
* @model id="true"
* @generated
*/
String getCard_identifier();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCard_identifier <em>Card identifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Card identifier</em>' attribute.
* @see #getCard_identifier()
* @generated
*/
void setCard_identifier(String value);
/**
* Returns the value of the '<em><b>Tax office</b></em>' attribute.
* The literals are from the enumeration {@link TaxationWithRoot.Tax_Office}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Tax office</em>' attribute.
* @see TaxationWithRoot.Tax_Office
* @see #setTax_office(Tax_Office)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_office()
* @model required="true"
* @generated
*/
Tax_Office getTax_office();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getTax_office <em>Tax office</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Tax office</em>' attribute.
* @see TaxationWithRoot.Tax_Office
* @see #getTax_office()
* @generated
*/
void setTax_office(Tax_Office value);
/**
* Returns the value of the '<em><b>Percentage of witholding</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Percentage of witholding</em>' attribute.
* @see #setPercentage_of_witholding(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Percentage_of_witholding()
* @model required="true"
* @generated
*/
double getPercentage_of_witholding();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getPercentage_of_witholding <em>Percentage of witholding</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Percentage of witholding</em>' attribute.
* @see #getPercentage_of_witholding()
* @generated
*/
void setPercentage_of_witholding(double value);
/**
* Returns the value of the '<em><b>Tax payers name surname</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Tax payers name surname</em>' attribute list.
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_payers_name_surname()
* @model ordered="false"
* @generated
*/
EList<String> getTax_payers_name_surname();
/**
* Returns the value of the '<em><b>Tax payers partner name surname</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Tax payers partner name surname</em>' attribute list.
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_payers_partner_name_surname()
* @model ordered="false"
* @generated
*/
EList<String> getTax_payers_partner_name_surname();
/**
* Returns the value of the '<em><b>Tax payers address</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Tax payers address</em>' reference.
* @see #setTax_payers_address(Address)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_payers_address()
* @model
* @generated
*/
Address getTax_payers_address();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getTax_payers_address <em>Tax payers address</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Tax payers address</em>' reference.
* @see #getTax_payers_address()
* @generated
*/
void setTax_payers_address(Address value);
/**
* Returns the value of the '<em><b>Jobs Employer SS No</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Jobs Employer SS No</em>' attribute.
* @see #setJobs_Employer_SSNo(String)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_Employer_SSNo()
* @model unique="false" ordered="false"
* @generated
*/
String getJobs_Employer_SSNo();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_Employer_SSNo <em>Jobs Employer SS No</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Jobs Employer SS No</em>' attribute.
* @see #getJobs_Employer_SSNo()
* @generated
*/
void setJobs_Employer_SSNo(String value);
/**
* Returns the value of the '<em><b>Jobs employers name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Jobs employers name</em>' attribute.
* @see #setJobs_employers_name(String)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_employers_name()
* @model unique="false" ordered="false"
* @generated
*/
String getJobs_employers_name();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_employers_name <em>Jobs employers name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Jobs employers name</em>' attribute.
* @see #getJobs_employers_name()
* @generated
*/
void setJobs_employers_name(String value);
/**
* Returns the value of the '<em><b>Jobs activity type</b></em>' attribute.
* The literals are from the enumeration {@link TaxationWithRoot.Job_Activity}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Jobs activity type</em>' attribute.
* @see TaxationWithRoot.Job_Activity
* @see #setJobs_activity_type(Job_Activity)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_activity_type()
* @model required="true"
* @generated
*/
Job_Activity getJobs_activity_type();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_activity_type <em>Jobs activity type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Jobs activity type</em>' attribute.
* @see TaxationWithRoot.Job_Activity
* @see #getJobs_activity_type()
* @generated
*/
void setJobs_activity_type(Job_Activity value);
/**
* Returns the value of the '<em><b>Jobs place of work</b></em>' attribute.
* The literals are from the enumeration {@link TaxationWithRoot.Town}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Jobs place of work</em>' attribute.
* @see TaxationWithRoot.Town
* @see #setJobs_place_of_work(Town)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_place_of_work()
* @model required="true"
* @generated
*/
Town getJobs_place_of_work();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_place_of_work <em>Jobs place of work</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Jobs place of work</em>' attribute.
* @see TaxationWithRoot.Town
* @see #getJobs_place_of_work()
* @generated
*/
<|fim▁hole|>
/**
* Returns the value of the '<em><b>Deduction FD daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction FD daily</em>' attribute.
* @see #setDeduction_FD_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FD_daily()
* @model default="0.0" unique="false" required="true" ordered="false"
* @generated
*/
double getDeduction_FD_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FD_daily <em>Deduction FD daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction FD daily</em>' attribute.
* @see #getDeduction_FD_daily()
* @generated
*/
void setDeduction_FD_daily(double value);
/**
* Returns the value of the '<em><b>Deduction FD monthly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction FD monthly</em>' attribute.
* @see #setDeduction_FD_monthly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FD_monthly()
* @model default="0.0" unique="false" required="true" ordered="false"
* @generated
*/
double getDeduction_FD_monthly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FD_monthly <em>Deduction FD monthly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction FD monthly</em>' attribute.
* @see #getDeduction_FD_monthly()
* @generated
*/
void setDeduction_FD_monthly(double value);
/**
* Returns the value of the '<em><b>Deduction AC daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction AC daily</em>' attribute.
* @see #setDeduction_AC_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_AC_daily()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_AC_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_AC_daily <em>Deduction AC daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction AC daily</em>' attribute.
* @see #getDeduction_AC_daily()
* @generated
*/
void setDeduction_AC_daily(double value);
/**
* Returns the value of the '<em><b>Deduction AC monthly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction AC monthly</em>' attribute.
* @see #setDeduction_AC_monthly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_AC_monthly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_AC_monthly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_AC_monthly <em>Deduction AC monthly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction AC monthly</em>' attribute.
* @see #getDeduction_AC_monthly()
* @generated
*/
void setDeduction_AC_monthly(double value);
/**
* Returns the value of the '<em><b>Deduction AC yearly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction AC yearly</em>' attribute.
* @see #setDeduction_AC_yearly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_AC_yearly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_AC_yearly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_AC_yearly <em>Deduction AC yearly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction AC yearly</em>' attribute.
* @see #getDeduction_AC_yearly()
* @generated
*/
void setDeduction_AC_yearly(double value);
/**
* Returns the value of the '<em><b>Deduction CE daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction CE daily</em>' attribute.
* @see #setDeduction_CE_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_CE_daily()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_CE_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_CE_daily <em>Deduction CE daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction CE daily</em>' attribute.
* @see #getDeduction_CE_daily()
* @generated
*/
void setDeduction_CE_daily(double value);
/**
* Returns the value of the '<em><b>Deduction CE monthly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction CE monthly</em>' attribute.
* @see #setDeduction_CE_monthly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_CE_monthly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_CE_monthly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_CE_monthly <em>Deduction CE monthly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction CE monthly</em>' attribute.
* @see #getDeduction_CE_monthly()
* @generated
*/
void setDeduction_CE_monthly(double value);
/**
* Returns the value of the '<em><b>Deduction CE yearly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction CE yearly</em>' attribute.
* @see #setDeduction_CE_yearly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_CE_yearly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_CE_yearly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_CE_yearly <em>Deduction CE yearly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction CE yearly</em>' attribute.
* @see #getDeduction_CE_yearly()
* @generated
*/
void setDeduction_CE_yearly(double value);
/**
* Returns the value of the '<em><b>Deduction DS daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction DS daily</em>' attribute.
* @see #setDeduction_DS_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_daily()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_DS_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_daily <em>Deduction DS daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction DS daily</em>' attribute.
* @see #getDeduction_DS_daily()
* @generated
*/
void setDeduction_DS_daily(double value);
/**
* Returns the value of the '<em><b>Deduction DS monthly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction DS monthly</em>' attribute.
* @see #setDeduction_DS_monthly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_monthly()
* @model default="0.0" required="true"
* @generated
*/
double getDeduction_DS_monthly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_monthly <em>Deduction DS monthly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction DS monthly</em>' attribute.
* @see #getDeduction_DS_monthly()
* @generated
*/
void setDeduction_DS_monthly(double value);
/**
* Returns the value of the '<em><b>Deduction FO daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction FO daily</em>' attribute.
* @see #setDeduction_FO_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FO_daily()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_FO_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FO_daily <em>Deduction FO daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction FO daily</em>' attribute.
* @see #getDeduction_FO_daily()
* @generated
*/
void setDeduction_FO_daily(double value);
/**
* Returns the value of the '<em><b>Deduction FO monthly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction FO monthly</em>' attribute.
* @see #setDeduction_FO_monthly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FO_monthly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_FO_monthly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FO_monthly <em>Deduction FO monthly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction FO monthly</em>' attribute.
* @see #getDeduction_FO_monthly()
* @generated
*/
void setDeduction_FO_monthly(double value);
/**
* Returns the value of the '<em><b>Deduction FO yearly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction FO yearly</em>' attribute.
* @see #setDeduction_FO_yearly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FO_yearly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getDeduction_FO_yearly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FO_yearly <em>Deduction FO yearly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction FO yearly</em>' attribute.
* @see #getDeduction_FO_yearly()
* @generated
*/
void setDeduction_FO_yearly(double value);
/**
* Returns the value of the '<em><b>Credit CIS daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Credit CIS daily</em>' attribute.
* @see #setCredit_CIS_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIS_daily()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getCredit_CIS_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIS_daily <em>Credit CIS daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Credit CIS daily</em>' attribute.
* @see #getCredit_CIS_daily()
* @generated
*/
void setCredit_CIS_daily(double value);
/**
* Returns the value of the '<em><b>Credit CIS monthly</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Credit CIS monthly</em>' attribute.
* @see #setCredit_CIS_monthly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIS_monthly()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getCredit_CIS_monthly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIS_monthly <em>Credit CIS monthly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Credit CIS monthly</em>' attribute.
* @see #getCredit_CIS_monthly()
* @generated
*/
void setCredit_CIS_monthly(double value);
/**
* Returns the value of the '<em><b>Credit CIM daily</b></em>' attribute.
* The default value is <code>"0.0"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Credit CIM daily</em>' attribute.
* @see #setCredit_CIM_daily(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIM_daily()
* @model default="0.0" unique="false" required="true"
* @generated
*/
double getCredit_CIM_daily();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIM_daily <em>Credit CIM daily</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Credit CIM daily</em>' attribute.
* @see #getCredit_CIM_daily()
* @generated
*/
void setCredit_CIM_daily(double value);
/**
* Returns the value of the '<em><b>Validity</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Validity</em>' attribute.
* @see #setValidity(boolean)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Validity()
* @model required="true"
* @generated
*/
boolean isValidity();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#isValidity <em>Validity</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Validity</em>' attribute.
* @see #isValidity()
* @generated
*/
void setValidity(boolean value);
/**
* Returns the value of the '<em><b>Income Tax Credit</b></em>' reference list.
* The list contents are of type {@link TaxationWithRoot.Income_Tax_Credit}.
* It is bidirectional and its opposite is '{@link TaxationWithRoot.Income_Tax_Credit#getTaxation_Frame <em>Taxation Frame</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Income Tax Credit</em>' reference list.
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Income_Tax_Credit()
* @see TaxationWithRoot.Income_Tax_Credit#getTaxation_Frame
* @model opposite="taxation_Frame" ordered="false"
* @generated
*/
EList<Income_Tax_Credit> getIncome_Tax_Credit();
/**
* Returns the value of the '<em><b>Previous</b></em>' reference.
* It is bidirectional and its opposite is '{@link TaxationWithRoot.Tax_Card#getCurrent_tax_card <em>Current tax card</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Previous</em>' reference.
* @see #setPrevious(Tax_Card)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Previous()
* @see TaxationWithRoot.Tax_Card#getCurrent_tax_card
* @model opposite="current_tax_card"
* @generated
*/
Tax_Card getPrevious();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getPrevious <em>Previous</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Previous</em>' reference.
* @see #getPrevious()
* @generated
*/
void setPrevious(Tax_Card value);
/**
* Returns the value of the '<em><b>Current tax card</b></em>' reference.
* It is bidirectional and its opposite is '{@link TaxationWithRoot.Tax_Card#getPrevious <em>Previous</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Current tax card</em>' reference.
* @see #setCurrent_tax_card(Tax_Card)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Current_tax_card()
* @see TaxationWithRoot.Tax_Card#getPrevious
* @model opposite="previous"
* @generated
*/
Tax_Card getCurrent_tax_card();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCurrent_tax_card <em>Current tax card</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Current tax card</em>' reference.
* @see #getCurrent_tax_card()
* @generated
*/
void setCurrent_tax_card(Tax_Card value);
/**
* Returns the value of the '<em><b>Credit CIM yearly</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Credit CIM yearly</em>' attribute.
* @see #setCredit_CIM_yearly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIM_yearly()
* @model required="true" ordered="false"
* @generated
*/
double getCredit_CIM_yearly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIM_yearly <em>Credit CIM yearly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Credit CIM yearly</em>' attribute.
* @see #getCredit_CIM_yearly()
* @generated
*/
void setCredit_CIM_yearly(double value);
/**
* Returns the value of the '<em><b>Deduction DS Alimony yearly</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction DS Alimony yearly</em>' attribute.
* @see #setDeduction_DS_Alimony_yearly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_Alimony_yearly()
* @model required="true" ordered="false"
* @generated
*/
double getDeduction_DS_Alimony_yearly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Alimony_yearly <em>Deduction DS Alimony yearly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction DS Alimony yearly</em>' attribute.
* @see #getDeduction_DS_Alimony_yearly()
* @generated
*/
void setDeduction_DS_Alimony_yearly(double value);
/**
* Returns the value of the '<em><b>Deduction DS Debt yearly</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Deduction DS Debt yearly</em>' attribute.
* @see #setDeduction_DS_Debt_yearly(double)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_Debt_yearly()
* @model required="true" ordered="false"
* @generated
*/
double getDeduction_DS_Debt_yearly();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Debt_yearly <em>Deduction DS Debt yearly</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Deduction DS Debt yearly</em>' attribute.
* @see #getDeduction_DS_Debt_yearly()
* @generated
*/
void setDeduction_DS_Debt_yearly(double value);
/**
* Returns the value of the '<em><b>Income</b></em>' container reference.
* It is bidirectional and its opposite is '{@link TaxationWithRoot.Income#getTax_card <em>Tax card</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Income</em>' container reference.
* @see #setIncome(Income)
* @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Income()
* @see TaxationWithRoot.Income#getTax_card
* @model opposite="tax_card" required="true" transient="false"
* @generated
*/
Income getIncome();
/**
* Sets the value of the '{@link TaxationWithRoot.Tax_Card#getIncome <em>Income</em>}' container reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Income</em>' container reference.
* @see #getIncome()
* @generated
*/
void setIncome(Income value);
} // Tax_Card<|fim▁end|> | void setJobs_place_of_work(Town value);
|
<|file_name|>loader.go<|end_file_name|><|fim▁begin|>// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package loader contains utilities for setting up the Vulkan loader.
package loader
import (
"context"
"io/ioutil"
"os"
"runtime"
"strings"
"github.com/google/gapid/core/app/layout"
"github.com/google/gapid/core/os/file"
"github.com/google/gapid/core/os/shell"
)
// SetupTrace sets up the environment for tracing a local app. Returns a
// clean-up function to be called after the trace completes, and a temporary
// filename that can be used to find the port if stdout fails, or an error.
func SetupTrace(ctx context.Context, env *shell.Env) (func(), string, error) {
lib, json, err := findLibraryAndJSON(ctx, layout.LibGraphicsSpy)
var f string
if err != nil {
return func() {}, f, err
}
cleanup, err := setupJSON(lib, json, env)
if err == nil {
if fl, e := ioutil.TempFile("", "gapii_port"); e == nil {
err = e
f = fl.Name()
fl.Close()
o := cleanup
cleanup = func() {
o()
os.Remove(f)
}
}
if err == nil {
env.Set("LD_PRELOAD", lib.System()).
AddPathStart("VK_INSTANCE_LAYERS", "VkGraphicsSpy").
AddPathStart("VK_DEVICE_LAYERS", "VkGraphicsSpy").
Set("GAPII_PORT_FILE", f)
if runtime.GOOS == "windows" {
// Adds the extra MSYS DLL dependencies onto the path.
// TODO: remove this hacky work-around.
// https://github.com/google/gapid/issues/17
gapit, err := layout.Gapit(ctx)<|fim▁hole|> if err == nil {
env.AddPathStart("PATH", gapit.Parent().System())
}
}
}
}
return cleanup, f, err
}
// SetupReplay sets up the environment for local replay. Returns a clean-up
// function to be called after replay completes, or an error.
func SetupReplay(ctx context.Context, env *shell.Env) (func(), error) {
lib, json, err := findLibraryAndJSON(ctx, layout.LibVirtualSwapChain)
if err != nil {
return func() {}, err
}
return setupJSON(lib, json, env)
}
func findLibraryAndJSON(ctx context.Context, libType layout.LibraryType) (file.Path, file.Path, error) {
lib, err := layout.Library(ctx, libType)
if err != nil {
return file.Path{}, file.Path{}, err
}
json, err := layout.Json(ctx, libType)
if err != nil {
return file.Path{}, file.Path{}, err
}
return lib, json, nil
}
func setupJSON(library, json file.Path, env *shell.Env) (func(), error) {
cleanup := func() {}
sourceContent, err := ioutil.ReadFile(json.System())
if err != nil {
return cleanup, err
}
tempdir, err := ioutil.TempDir("", "gapit_dir")
if err != nil {
return cleanup, err
}
cleanup = func() {
os.RemoveAll(tempdir)
}
libName := strings.Replace(library.System(), "\\", "\\\\", -1)
fixedContent := strings.Replace(string(sourceContent[:]), "<library>", libName, 1)
ioutil.WriteFile(tempdir+"/"+json.Basename(), []byte(fixedContent), 0644)
env.AddPathStart("VK_LAYER_PATH", tempdir)
return cleanup, nil
}<|fim▁end|> | |
<|file_name|>test_active_config_holder.py<|end_file_name|><|fim▁begin|># This file is part of the ISIS IBEX application.
# Copyright (C) 2012-2016 Science & Technology Facilities Council.
# All rights reserved.
#
# This program is distributed in the hope that it will be useful.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v1.0 which accompanies this distribution.
# EXCEPT AS EXPRESSLY SET FORTH IN THE ECLIPSE PUBLIC LICENSE V1.0, THE PROGRAM
# AND ACCOMPANYING MATERIALS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND. See the Eclipse Public License v1.0 for more details.
#
# You should have received a copy of the Eclipse Public License v1.0
# along with this program; if not, you can obtain a copy from
# https://www.eclipse.org/org/documents/epl-v10.php or
# http://opensource.org/licenses/eclipse-1.0.php
import unittest
import json
import os
from mock import Mock
from parameterized import parameterized
from BlockServer.config.block import Block
from BlockServer.config.configuration import Configuration
from BlockServer.config.ioc import IOC
from BlockServer.core.active_config_holder import (ActiveConfigHolder, _blocks_changed, _blocks_changed_in_config,
_compare_ioc_properties)
from BlockServer.mocks.mock_ioc_control import MockIocControl
from BlockServer.core.macros import MACROS
from BlockServer.mocks.mock_file_manager import MockConfigurationFileManager
from BlockServer.test_modules.helpers import modify_active
from server_common.constants import IS_LINUX
CONFIG_PATH = "./test_configs/"
BASE_PATH = "./example_base/"
# Helper methods
def quick_block_to_json(name, pv, group, local=True):
return {
'name': name,
'pv': pv,
'group': group,
'local': local
}
def add_basic_blocks_and_iocs(config_holder):
config_holder.add_block(quick_block_to_json("TESTBLOCK1", "PV1", "GROUP1", True))
config_holder.add_block(quick_block_to_json("TESTBLOCK2", "PV2", "GROUP2", True))
config_holder.add_block(quick_block_to_json("TESTBLOCK3", "PV3", "GROUP2", True))
config_holder.add_block(quick_block_to_json("TESTBLOCK4", "PV4", "NONE", True))
config_holder._add_ioc("SIMPLE1")
config_holder._add_ioc("SIMPLE2")
def get_groups_and_blocks(jsondata):
return json.loads(jsondata)
def create_grouping(groups):
return json.dumps([{"name": group, "blocks": blocks} for group, blocks in groups.items()])
def create_dummy_component():
config = Configuration(MACROS)
config.add_block("COMPBLOCK1", "PV1", "GROUP1", True)
config.add_block("COMPBLOCK2", "PV2", "COMPGROUP", True)
config.add_ioc("COMPSIMPLE1")
config.is_component = True
return config
# Note that the ActiveConfigServerManager contains an instance of the Configuration class and hands a lot of
# work off to this object. Rather than testing whether the functionality in the configuration class works
# correctly (e.g. by checking that a block has been edited properly after calling configuration.edit_block),
# we should instead test that ActiveConfigServerManager passes the correct parameters to the Configuration object.
# We are testing that ActiveConfigServerManager correctly interfaces with Configuration, not testing the
# functionality of Configuration, which is done in Configuration's own suite of tests.
class TestActiveConfigHolderSequence(unittest.TestCase):
def setUp(self):
# Note: All configurations are saved in memory
self.mock_archive = Mock()
self.mock_archive.update_archiver = Mock()
self.mock_file_manager = MockConfigurationFileManager()
self.active_config_holder = self.create_active_config_holder()
def create_active_config_holder(self):
config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "settings")
return ActiveConfigHolder(MACROS, self.mock_archive, self.mock_file_manager, MockIocControl(""), config_dir)
def test_add_ioc(self):
config_holder = self.active_config_holder
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder._add_ioc("SIMPLE1")
config_holder._add_ioc("SIMPLE2")
iocs = config_holder.get_ioc_names()
self.assertTrue("SIMPLE1" in iocs)
self.assertTrue("SIMPLE2" in iocs)
@unittest.skipIf(IS_LINUX, "Unable to save config on Linux")
def test_save_config(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
try:
config_holder.save_active("TEST_CONFIG")
except Exception as e:
self.fail(f"test_save_config raised Exception unexpectedly: {e}")
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_load_config(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_CONFIG")
config_holder.clear_config()
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 0)
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder.load_active("TEST_CONFIG")
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 4)
self.assertTrue('TESTBLOCK1' in blocks)
self.assertTrue('TESTBLOCK2' in blocks)
self.assertTrue('TESTBLOCK3' in blocks)
self.assertTrue('TESTBLOCK4' in blocks)
iocs = config_holder.get_ioc_names()
self.assertTrue("SIMPLE1" in iocs)
self.assertTrue("SIMPLE2" in iocs)
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_GIVEN_load_config_WHEN_load_config_again_THEN_no_ioc_changes(self):
# This test is checking that a load will correctly cache the IOCs that are running so that a comparison will
# return no change
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_CONFIG")
config_holder.clear_config()
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 0)
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder.load_active("TEST_CONFIG")
config_holder.load_active("TEST_CONFIG")
iocs_to_start, iocs_to_restart, iocs_to_stop = config_holder.iocs_changed()
self.assertEqual(len(iocs_to_start), 0)
self.assertEqual(len(iocs_to_restart), 0)
self.assertEqual(len(iocs_to_stop), 0)
def test_load_notexistant_config(self):
config_holder = self.active_config_holder
self.assertRaises(IOError, lambda: config_holder.load_active("DOES_NOT_EXIST"))
def test_save_as_component(self):
config_holder = self.active_config_holder
try:
config_holder.save_active("TEST_CONFIG1", as_comp=True)
except Exception as e:
self.fail(f"test_save_as_component raised Exception unexpectedly: {e}")
@unittest.skipIf(IS_LINUX, "Unable to save config on Linux")
def test_save_config_for_component(self):
config_holder = self.active_config_holder
config_holder.save_active("TEST_CONFIG1", as_comp=True)
try:
config_holder.save_active("TEST_CONFIG1")
except Exception as e:
self.fail(f"test_save_config_for_component raised Exception unexpectedly: {e}")
def test_load_component_fails(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_COMPONENT", as_comp=True)
config_holder.clear_config()
self.assertRaises(IOError, lambda: config_holder.load_active("TEST_COMPONENT"))
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_load_last_config(self):
config_holder = self.active_config_holder
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active("TEST_CONFIG")
config_holder.clear_config()
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 0)
iocs = config_holder.get_ioc_names()
self.assertEqual(len(iocs), 0)
config_holder.load_last_config()
grps = config_holder.get_group_details()
self.assertTrue(len(grps) == 3)
blocks = config_holder.get_blocknames()
self.assertEqual(len(blocks), 4)
self.assertTrue('TESTBLOCK1' in blocks)
self.assertTrue('TESTBLOCK2' in blocks)
self.assertTrue('TESTBLOCK3' in blocks)
self.assertTrue('TESTBLOCK4' in blocks)
iocs = config_holder.get_ioc_names()
self.assertTrue("SIMPLE1" in iocs)
self.assertTrue("SIMPLE2" in iocs)
def test_reloading_current_config_with_blank_name_does_nothing(self):
# arrange
config_name = self.active_config_holder.get_config_name()
self.assertEqual(config_name, "")
load_requests = self.mock_file_manager.get_load_config_history()
self.assertEqual(len(load_requests), 0)
# act
self.active_config_holder.reload_current_config()
# assert
load_requests = self.mock_file_manager.get_load_config_history()
self.assertEqual(len(load_requests), 0)
@unittest.skipIf(IS_LINUX, "Location of last_config.txt not correctly configured on Linux")
def test_reloading_current_config_sends_load_request_correctly(self):
# arrange
config_holder = self.active_config_holder
config_name = "TEST_CONFIG"
add_basic_blocks_and_iocs(config_holder)
config_holder.save_active(config_name)
load_requests = self.mock_file_manager.get_load_config_history()
self.assertEqual(len(load_requests), 0)
# act
config_holder.reload_current_config()
# assert
load_requests = self.mock_file_manager.get_load_config_history()
self.assertEqual(load_requests.count(config_name), 1)
def _modify_active(self, config_holder, new_details, name="config1"):
modify_active(name, MACROS, self.mock_file_manager, new_details, config_holder)
def test_iocs_changed_no_changes(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
self._modify_active(config_holder, details)
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 0)
self.assertEqual(len(stop), 0)
def test_iocs_changed_ioc_added(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
# Act
details['iocs'].append(IOC("NAME"))
self._modify_active(config_holder, details)
# Assert
start, restart, stop = config_holder.iocs_changed()<|fim▁hole|> self.assertEqual(len(start), 1)
self.assertEqual(len(restart), 0)
self.assertEqual(len(stop), 0)
def test_iocs_changed_ioc_removed(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['iocs'].append(IOC("NAME"))
self._modify_active(config_holder, details)
# Act
details['iocs'].pop(0)
self._modify_active(config_holder, details)
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 0)
self.assertEqual(len(stop), 1)
def test_GIVEN_an_ioc_defined_in_a_component_WHEN_the_component_is_removed_THEN_the_ioc_is_stopped(self):
# Arrange
config_holder = self.create_active_config_holder()
component = create_dummy_component()
component.iocs = {"DUMMY_IOC": IOC("dummyname")}
self.mock_file_manager.comps["component_name"] = component
config_holder.add_component("component_name")
details = config_holder.get_config_details()
details["blocks"] = [block for block in details["blocks"] if block["component"] is None]
self._modify_active(config_holder, details)
# Act
config_holder.remove_comp("component_name")
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 0)
self.assertEqual(len(stop), 1)
def test_GIVEN_an_ioc_defined_in_a_component_WHEN_the_ioc_simlevel_is_changed_THEN_the_ioc_is_restarted(self):
# Arrange
config_holder = self.create_active_config_holder()
component = create_dummy_component()
component.iocs = {"DUMMY_IOC": IOC("dummyname", simlevel="devsim")}
self.mock_file_manager.comps["component_name"] = component
config_holder.add_component("component_name")
details = config_holder.get_config_details()
details["blocks"] = [block for block in details["blocks"] if block["component"] is None]
self._modify_active(config_holder, details)
# Act
config_holder.remove_comp("component_name")
new_component = create_dummy_component()
new_component.iocs = {"DUMMY_IOC": IOC("dummyname", simlevel="recsim")} # Change simlevel
self.mock_file_manager.comps["component_name"] = new_component
config_holder.add_component("component_name")
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 1)
self.assertEqual(len(stop), 0)
def test_GIVEN_an_ioc_defined_in_a_component_WHEN_the_ioc_macros_are_changed_THEN_the_ioc_is_restarted(self):
# Arrange
config_holder = self.create_active_config_holder()
component = create_dummy_component()
component.iocs = {"DUMMY_IOC": IOC("dummyname", macros={"macros": {"A_MACRO": "VALUE1"}})}
self.mock_file_manager.comps["component_name"] = component
config_holder.add_component("component_name")
details = config_holder.get_config_details()
details["blocks"] = [block for block in details["blocks"] if block["component"] is None]
self._modify_active(config_holder, details)
# Act
config_holder.remove_comp("component_name")
new_component = create_dummy_component()
new_component.iocs = {"DUMMY_IOC": IOC("dummyname", macros={"macros": {"A_MACRO": "VALUE2"}})}
self.mock_file_manager.comps["component_name"] = new_component
config_holder.add_component("component_name")
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 1)
self.assertEqual(len(stop), 0)
def test_GIVEN_an_ioc_defined_in_a_component_WHEN_the_ioc_macros_are_not_changed_THEN_the_ioc_is_not_restarted(self):
# Arrange
config_holder = self.create_active_config_holder()
component = create_dummy_component()
component.iocs = {"DUMMY_IOC": IOC("dummyname", macros={"macros": {"A_MACRO": "VALUE1"}})}
self.mock_file_manager.comps["component_name"] = component
config_holder.add_component("component_name")
details = config_holder.get_config_details()
details["blocks"] = [block for block in details["blocks"] if block["component"] is None]
self._modify_active(config_holder, details)
# Act
config_holder.remove_comp("component_name")
new_component = create_dummy_component()
new_component.iocs = {"DUMMY_IOC": IOC("dummyname", macros={"macros": {"A_MACRO": "VALUE1"}})}
self.mock_file_manager.comps["component_name"] = new_component
config_holder.add_component("component_name")
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 0)
self.assertEqual(len(stop), 0)
def test_GIVEN_an_ioc_defined_in_the_top_level_config_WHEN_the_ioc_is_removed_THEN_the_ioc_is_stopped(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['iocs'].append(IOC("NAME"))
self._modify_active(config_holder, details)
# Act
details['iocs'].pop(0)
self._modify_active(config_holder, details)
# Assert
start, restart, stop = config_holder.iocs_changed()
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 0)
self.assertEqual(len(stop), 1)
def test_given_empty_config_when_block_added_then_blocks_changed_returns_true(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
# Act
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Assert
self.assertTrue(config_holder.blocks_changed())
def test_given_config_when_block_params_changed_then_blocks_changed_returns_true(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Act
details['blocks'][0]['local'] = False
self._modify_active(config_holder, details)
# Assert
self.assertTrue(config_holder.blocks_changed())
def test_given_config_with_one_block_when_block_removed_then_blocks_changed_returns_true(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Act
details['blocks'].pop(0)
self._modify_active(config_holder, details)
# Assert
self.assertTrue(config_holder.blocks_changed())
def test_given_empty_config_when_component_added_then_blocks_changed_returns_true(self):
# Arrange
config_holder = self.create_active_config_holder()
# Act
self.mock_file_manager.comps["component_name"] = create_dummy_component()
config_holder.add_component("component_name")
# Assert
self.assertTrue(config_holder.blocks_changed())
def test_given_empty_config_when_no_change_then_blocks_changed_returns_false(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
# Act
self._modify_active(config_holder, details)
# Assert
self.assertFalse(config_holder.blocks_changed())
def test_given_config_when_no_change_then_blocks_changed_returns_false(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Act
self._modify_active(config_holder, details)
# Assert
self.assertFalse(config_holder.blocks_changed())
def test_given_no_blocks_changed_when_update_archiver_archiver_not_restarted(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Act
self._modify_active(config_holder, details)
config_holder.update_archiver()
# Assert
self.assertFalse(self.mock_archive.update_archiver.called)
def test_given_blocks_changed_when_update_archiver_archiver_is_restarted(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Act
details['blocks'].append(Block(name="TESTNAME2", pv="TESTPV2").to_dict())
self._modify_active(config_holder, details)
config_holder.update_archiver()
# Assert
self.assertTrue(self.mock_archive.update_archiver.called)
def test_given_no_blocks_changed_but_full_init_when_update_archiver_archiver_is_restarted(self):
# Arrange
config_holder = self.create_active_config_holder()
details = config_holder.get_config_details()
details['blocks'].append(Block(name="TESTNAME", pv="TESTPV").to_dict())
self._modify_active(config_holder, details)
# Act
self._modify_active(config_holder, details)
config_holder.update_archiver(True)
# Assert
self.assertTrue(self.mock_archive.update_archiver.called)
@parameterized.expand([
(Block(name="name", pv="pv"), Block(name="other", pv="pv")),
(Block(name="name", pv="pv"), Block(name="name", pv="other")),
(Block(name="name", pv="pv", local=True), Block(name="name", pv="pv", local=False)),
(Block(name="name", pv="pv", component="A"), Block(name="name", pv="pv", component="B")),
(Block(name="name", pv="pv", runcontrol=True), Block(name="name", pv="pv", runcontrol=False)),
(Block(name="name", pv="pv", lowlimit=True), Block(name="name", pv="pv", lowlimit=False)),
(Block(name="name", pv="pv", highlimit=True), Block(name="name", pv="pv", highlimit=False)),
(Block(name="name", pv="pv", log_periodic=True), Block(name="name", pv="pv", log_periodic=False)),
(Block(name="name", pv="pv", log_rate=True), Block(name="name", pv="pv", log_rate=False)),
(Block(name="name", pv="pv", log_deadband=True), Block(name="name", pv="pv", log_deadband=False)),
])
def test_WHEN_block_attributes_different_THEN_blocks_changed_returns_true(self, block1, block2):
self.assertTrue(_blocks_changed(block1, block2))
def test_WHEN_block_attributes_different_THEN_blocks_changed_returns_false(self):
self.assertFalse(_blocks_changed(Block(name="name", pv="pv"), Block(name="name", pv="pv")))
def test_WHEN_blocks_changed_in_config_called_for_configs_which_contain_same_blocks_THEN_returns_false(self):
config1 = Mock()
config1.blocks = {"a": Block(name="a", pv="pv")}
config2 = Mock()
config2.blocks = {"a": Block(name="a", pv="pv")}
self.assertFalse(_blocks_changed_in_config(config1, config2))
def test_WHEN_blocks_changed_in_config_called_for_configs_with_removed_blocks_THEN_returns_true(self):
config1 = Mock()
config1.blocks = {"a": Block(name="a", pv="pv")}
config2 = Mock()
config2.blocks = {}
self.assertTrue(_blocks_changed_in_config(config1, config2))
def test_WHEN_blocks_changed_in_config_called_for_configs_with_added_blocks_THEN_returns_true(self):
config1 = Mock()
config1.blocks = {}
config2 = Mock()
config2.blocks = {"a": Block(name="a", pv="pv")}
self.assertTrue(_blocks_changed_in_config(config1, config2))
def test_WHEN_blocks_changed_in_config_called_and_block_comparator_says_they_are_different_THEN_returns_true(self):
config1 = Mock()
config1.blocks = {"a": Block(name="a", pv="pv")}
config2 = Mock()
config2.blocks = {"a": Block(name="a", pv="pv")}
self.assertTrue(_blocks_changed_in_config(config1, config2, block_comparator=lambda block1, block2: True))
def test_WHEN_blocks_changed_in_config_called_and_block_comparator_says_they_are_the_same_THEN_returns_false(self):
config1 = Mock()
config1.blocks = {"a": Block(name="a", pv="pv")}
config2 = Mock()
config2.blocks = {"a": Block(name="a", pv="pv")}
self.assertFalse(_blocks_changed_in_config(config1, config2, block_comparator=lambda block1, block2: False))
def test_WHEN_compare_ioc_properties_called_with_the_same_ioc_then_returns_empty_set_of_iocs_to_start_restart(self):
old_config = Mock()
old_config.iocs = {"a": IOC("a")}
new_config = Mock()
new_config.iocs = {"a": IOC("a")}
start, restart = _compare_ioc_properties(old_config, new_config)
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 0)
@parameterized.expand([
({"a": IOC("a", macros=True)}, {"a": IOC("a", macros=False)}),
({"a": IOC("a", pvs=True)}, {"a": IOC("a", pvs=False)}),
({"a": IOC("a", pvsets=True)}, {"a": IOC("a", pvsets=False)}),
({"a": IOC("a", simlevel="recsim")}, {"a": IOC("a", simlevel="devsim")}),
({"a": IOC("a", restart=True)}, {"a": IOC("a", restart=False)}),
])
def test_WHEN_compare_ioc_properties_called_with_different_then_restarts_ioc(self, old_iocs, new_iocs):
old_config = Mock()
old_config.iocs = old_iocs
new_config = Mock()
new_config.iocs = new_iocs
start, restart = _compare_ioc_properties(old_config, new_config)
self.assertEqual(len(start), 0)
self.assertEqual(len(restart), 1)
def test_WHEN_compare_ioc_properties_called_with_new_ioc_then_starts_new_ioc(self):
old_config = Mock()
old_config.iocs = {}
new_config = Mock()
new_config.iocs = {"a": IOC("a", macros=True)}
start, restart = _compare_ioc_properties(old_config, new_config)
self.assertEqual(len(start), 1)
self.assertEqual(len(restart), 0)
if __name__ == '__main__':
# Run tests
unittest.main()<|fim▁end|> | |
<|file_name|>mapping.py<|end_file_name|><|fim▁begin|>'''
This module is part of ngs_backbone. This module provide mapping related
analyses
Created on 15/03/2010
@author: peio
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of franklin.
# franklin is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# franklin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with franklin. If not, see <http://www.gnu.org/licenses/>.
import os, shutil
from gzip import GzipFile
from tempfile import NamedTemporaryFile
from franklin.backbone.analysis import (Analyzer, scrape_info_from_fname,
_LastAnalysisAnalyzer)
from franklin.mapping import map_reads
from franklin.utils.cmd_utils import call
from franklin.utils.misc_utils import (NamedTemporaryDir, VersionedPath,
rel_symlink)
from franklin.backbone.specifications import (BACKBONE_BASENAMES,
PLOT_FILE_FORMAT,
BACKBONE_DIRECTORIES)
from franklin.sam import (bam2sam, add_header_and_tags_to_sam, merge_sam,
sam2bam, sort_bam_sam, standardize_sam, realign_bam,
bam_distribs, create_bam_index, bam_general_stats)
class SetAssemblyAsReferenceAnalyzer(Analyzer):
'It sets the reference assembly as mapping reference'
def run(self):
'''It runs the analysis.'''
contigs_path = self._get_input_fpaths()['contigs']
contigs_ext = contigs_path.extension
reference_dir = self._create_output_dirs()['result']
reference_fpath = os.path.join(reference_dir,
BACKBONE_BASENAMES['mapping_reference'] + '.' + \
contigs_ext)
if os.path.exists(reference_fpath):
os.remove(reference_fpath)
rel_symlink(contigs_path.last_version, reference_fpath)
def _get_basename(fpath):
'It returns the base name without path and extension'
return os.path.splitext(os.path.basename(fpath))[0]
class MappingAnalyzer(Analyzer):
'It performs the mapping of the sequences to the reference'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
project_settings = self._project_settings
settings = project_settings['Mappers']
tmp_dir = project_settings['General_settings']['tmpdir']
project_path = project_settings['General_settings']['project_path']
unmapped_fhand = None
if 'keep_unmapped_reads_in_bam' in settings:
if settings['keep_unmapped_reads_in_bam'] == False:
unmapped_fpath = os.path.join(project_path,
BACKBONE_DIRECTORIES['mappings'][0],
BACKBONE_BASENAMES['unmapped_list'])
unmapped_fhand = GzipFile(unmapped_fpath, 'w')
inputs = self._get_input_fpaths()
reads_fpaths = inputs['reads']
output_dir = self._create_output_dirs(timestamped=True)['result']
# define color and sequence references
reference_path = inputs['reference']
mapping_index_dir = inputs['mapping_index']
#print reference_path, mapping_index_dir
#memory for the java programs
java_mem = self._project_settings['Other_settings']['java_memory']
picard_path = self._project_settings['Other_settings']['picard_path']
for read_fpath in reads_fpaths:
mapping_parameters = {}
read_info = scrape_info_from_fname(read_fpath)
platform = read_info['pl']
#which maper are we using for this platform
mapper = settings['mapper_for_%s' % platform]
(reference_fpath,
color_space) = self._prepare_mapper_index(mapping_index_dir,
reference_path,
platform, mapper)
mapping_parameters['unmapped_fhand'] = unmapped_fhand
mapping_parameters['colorspace'] = color_space
out_bam_fpath = os.path.join(output_dir,
read_fpath.basename + '.bam')
if platform in ('454', 'sanger'):
mapping_parameters['reads_length'] = 'long'
else:
mapping_parameters['reads_length'] = 'short'
if not os.path.exists(out_bam_fpath):
mapping_parameters['threads'] = self.threads
mapping_parameters['java_conf'] = {'java_memory':java_mem,
'picard_path':picard_path}
mapping_parameters['tmp_dir'] = tmp_dir
map_reads(mapper,
reads_fpath=read_fpath.last_version,
reference_fpath=reference_fpath,
out_bam_fpath=out_bam_fpath,
parameters=mapping_parameters)
# Now we run the select _last mapping
self._spawn_analysis(DEFINITIONS['_select_last_mapping'],
silent=self._silent)
self._log({'analysis_finished':True})
def _prepare_mapper_index(self, mapping_index_dir, reference_path, platform,
mapper):
'It creates reference_fpath depending on the mapper and the platform'
kind = 'color' if platform == 'solid' else 'sequence'
color_space = True if kind == 'color' else False
mapping_index_dir = mapping_index_dir[0].original_path
index_dir = mapping_index_dir % (mapper, kind)
if not os.path.exists(index_dir):
os.mkdir(index_dir)
reference_fpath = reference_path.last_version
reference_fname = os.path.basename(reference_fpath)
index_fpath = os.path.join(index_dir, reference_fname)
if not os.path.exists(index_fpath):
rel_symlink(reference_fpath, index_fpath)
return index_fpath, color_space
class MergeBamAnalyzer(Analyzer):
'It performs the merge of various bams into only one'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
settings = self._project_settings
project_path = settings['General_settings']['project_path']
tmp_dir = settings['General_settings']['tmpdir']
inputs = self._get_input_fpaths()
bam_paths = inputs['bams']
reference_path = inputs['reference']
output_dir = self._create_output_dirs()['result']
merged_bam_path = VersionedPath(os.path.join(output_dir,
BACKBONE_BASENAMES['merged_bam']))
merged_bam_fpath = merged_bam_path.next_version
#Do we have to add the default qualities to the sam file?
#do we have characters different from ACTGN?
add_qualities = settings['Sam_processing']['add_default_qualities']
#memory for the java programs
java_mem = settings['Other_settings']['java_memory']
picard_path = settings['Other_settings']['picard_path']
if add_qualities:
default_sanger_quality = settings['Other_settings']['default_sanger_quality']
default_sanger_quality = int(default_sanger_quality)
else:
default_sanger_quality = None
temp_dir = NamedTemporaryDir()
for bam_path in bam_paths:
bam_basename = bam_path.basename
temp_sam = NamedTemporaryFile(prefix='%s.' % bam_basename,
suffix='.sam')
sam_fpath = os.path.join(temp_dir.name, bam_basename + '.sam')
bam2sam(bam_path.last_version, temp_sam.name)
sam_fhand = open(sam_fpath, 'w')
# First we need to create the sam with added tags and headers
add_header_and_tags_to_sam(temp_sam, sam_fhand)
temp_sam.close()
sam_fhand.close()
#the standardization
temp_sam2 = NamedTemporaryFile(prefix='%s.' % bam_basename,
suffix='.sam', delete=False)
standardize_sam(open(sam_fhand.name), temp_sam2,
default_sanger_quality,
add_def_qual=add_qualities,
only_std_char=True)
temp_sam2.flush()
shutil.move(temp_sam2.name, sam_fhand.name)
temp_sam2.close()
get_sam_fpaths = lambda dir_: [os.path.join(dir_, fname) for fname in os.listdir(dir_) if fname.endswith('.sam')]
# Once the headers are ready we are going to merge
sams = get_sam_fpaths(temp_dir.name)
sams = [open(sam) for sam in sams]
temp_sam = NamedTemporaryFile(suffix='.sam')
reference_fhand = open(reference_path.last_version)
try:
merge_sam(sams, temp_sam, reference_fhand)
except Exception:
if os.path.exists(merged_bam_fpath):
os.remove(merged_bam_fpath)
raise
reference_fhand.close()
# close files
for sam in sams:
sam.close()
# Convert sam into a bam,(Temporary)
temp_bam = NamedTemporaryFile(suffix='.bam')
sam2bam(temp_sam.name, temp_bam.name)
# finally we need to order the bam
#print 'unsorted.bam', temp_bam.name
#raw_input()
sort_bam_sam(temp_bam.name, merged_bam_fpath,
java_conf={'java_memory':java_mem,
'picard_path':picard_path}, tmp_dir=tmp_dir )
temp_bam.close()
temp_sam.close()
create_bam_index(merged_bam_fpath)
self._log({'analysis_finished':True})
class CalmdBamAnalyzer(Analyzer):
'It runs samtools calmd '
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
inputs = self._get_input_fpaths()
bam_path = inputs['bam']
bam_fpath = bam_path.last_version
reference_fpath = inputs['reference'].last_version
out_fhand = open(bam_path.next_version, 'w')
cmd = ['samtools', 'calmd', '-Abr', bam_fpath, reference_fpath]
call(cmd, raise_on_error=True, stdout=out_fhand)
create_bam_index(out_fhand.name)
out_fhand.close()
self._log({'analysis_finished':True})
class RealignBamAnalyzer(Analyzer):
'It realigns the bam using GATK'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
settings = self._project_settings
project_path = settings['General_settings']['project_path']
tmp_dir = settings['General_settings']['tmpdir']
inputs = self._get_input_fpaths()
bam_path = inputs['bam']
bam_fpath = bam_path.last_version
reference_path = inputs['reference']
#memory for the java programs
osettings = settings['Other_settings']
java_mem = osettings['java_memory']
picard_path = osettings['picard_path']<|fim▁hole|> #we need a temporary path
temp_bam = NamedTemporaryFile(suffix='.bam')
temp_bam_fpath = temp_bam.name
temp_bam.close()
#do the realigment
realign_bam(bam_fpath=bam_fpath,
reference_fpath=reference_path.last_version,
out_bam_fpath=temp_bam_fpath,
java_conf={'java_memory':java_mem,
'picard_path':picard_path,
'gatk_path':gatk_path},
threads=self.threads,
tmp_dir=tmp_dir)
#a new version for the original bam
out_bam_fpath = bam_path.next_version
shutil.move(temp_bam_fpath, out_bam_fpath)
self._log({'analysis_finished':True})
class BamStatsAnalyzer(Analyzer):
'It makes the stats of the mapping'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
settings = self._project_settings
self._create_output_dirs()['result']
project_name = settings['General_settings']['project_name']
sample_size = settings['Sam_stats']['sampling_size']
project_path = settings['General_settings']['project_path']
inputs = self._get_input_fpaths()
bam_path = inputs['bam']
bam_fpath = bam_path.last_version
bam_fhand = open(bam_fpath)
out_dir = os.path.abspath(self._get_output_dirs()['result'])
summary_fname = os.path.join(out_dir,
BACKBONE_BASENAMES['statistics_file'])
summary_fhand = open(summary_fname, 'w')
# non mapped_reads_fhand
unmapped_fpath = os.path.join(project_path,
BACKBONE_DIRECTORIES['mappings'][0],
BACKBONE_BASENAMES['unmapped_list'])
if os.path.exists(unmapped_fpath):
unmapped_fhand = GzipFile(unmapped_fpath)
else:
unmapped_fhand = None
#The general statistics
bam_general_stats(bam_fhand, summary_fhand, unmapped_fhand)
for kind in ('coverage', 'mapq'):
basename = os.path.join(out_dir, "%s" % (project_name))
bam_fhand.seek(0)
bam_distribs(bam_fhand, kind, basename=basename,
sample_size=sample_size, summary_fhand=summary_fhand,
plot_file_format=PLOT_FILE_FORMAT)
bam_fhand.close()
if unmapped_fhand is not None:
unmapped_fhand.close()
DEFINITIONS = {
'set_assembly_as_reference':
{'inputs':{
'contigs':
{'directory': 'assembly_result',
'file': 'contigs'},
},
'outputs':{'result':{'directory': 'mapping_reference'}},
'analyzer': SetAssemblyAsReferenceAnalyzer,
},
'mapping':
{'inputs':{
'reads':
{'directory': 'cleaned_reads',
'file_kinds': 'sequence_files'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
'mapping_index':
{'directory': 'mapping_index'},
},
'outputs':{'result':{'directory': 'mappings_by_readgroup'}},
'analyzer': MappingAnalyzer,
},
'_select_last_mapping':
{'inputs':{'analyses_dir':{'directory': 'mappings'}},
'outputs':{'result':{'directory': 'mapping_result',
'create':False}},
'analyzer': _LastAnalysisAnalyzer,
},
'merge_bams':
{'inputs':{
'bams':
{'directory': 'mappings_by_readgroup',
'file_kinds': 'bam'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
},
'outputs':{'result':{'directory': 'mapping_result'}},
'analyzer': MergeBamAnalyzer,
},
'realign_bam':
{'inputs':{
'bam':
{'directory': 'mapping_result',
'file': 'merged_bam'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
},
'outputs':{'result':{'directory': 'mapping_result'}},
'analyzer': RealignBamAnalyzer,
},
'calmd_bam':
{'inputs':{
'bam':
{'directory': 'mapping_result',
'file': 'merged_bam'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
},
'outputs':{'result':{'directory': 'mapping_result'}},
'analyzer': CalmdBamAnalyzer,
},
'mapping_stats':
{'inputs':{
'bam':
{'directory': 'mapping_result',
'file': 'merged_bam'},
},
'outputs':{'result':{'directory': 'mapping_stats'}},
'analyzer': BamStatsAnalyzer,
},
}<|fim▁end|> | gatk_path = osettings['gatk_path']
|
<|file_name|>conftest.py<|end_file_name|><|fim▁begin|>import pytest
import sys
import logging
from sqlalchemy import create_engine
import zk.model.meta as zkmeta
import zkpylons.model.meta as pymeta
from zkpylons.config.routing import make_map
from paste.deploy import loadapp
from webtest import TestApp
from paste.fixture import Dummy_smtplib
from .fixtures import ConfigFactory
from ConfigParser import ConfigParser
# Get settings from config file, only need it once
ini = ConfigParser()
ini_filename = "test.ini"
ini.read(ini_filename)
# Logging displayed by passing -s to pytest
#logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
@pytest.yield_fixture
def map():
config = {
'pylons.paths' : { 'controllers' : None },
'debug' : True,
}
yield make_map(config)
@pytest.yield_fixture
def app():
wsgiapp = loadapp('config:'+ini_filename, relative_to=".")
app = TestApp(wsgiapp)
yield app
class DoubleSession(object):
# There is an issue with the zkpylons -> zk migration
# Some files use zk.model, which uses zk.model.meta.Session
# Some files use zkpylons.model, which uses zkpylons.model.meta.Session
# Some files use relative paths, which means you can kinda guess at it
# The best way around this is to configure both Session objects
# But then operations frequently have to be applied to both
# This class wraps operations needed for testing, and applies both
def __init__(self, session1, session2):
self.s1 = session1
self.s2 = session2
def remove(self):
self.s1.remove()
self.s2.remove()
def configure(self, engine):
self.s1.configure(bind=engine)
self.s2.configure(bind=engine)
self.s1.configure(autoflush=False)
self.s2.configure(autoflush=False)
def commit(self):
self.s1.commit()
self.s2.commit()
# TODO: Maybe expire_all or refresh would be better
def expunge_all(self):
self.s1.expunge_all()
self.s2.expunge_all()
def query(self, cls):
return self.s1.query(cls)
def execute(self, *args, **kwargs):
return self.s1.execute(*args, **kwargs)
base_general_config = {
'sponsors' : {"top":[],"slideshow":[]},
'account_creation' : True,
'cfp_status' : "open",
'conference_status' : "open",
}<|fim▁hole|>
base_rego_config = {
'personal_info' : {"phone":"yes","home_address":"yes"}
}
@pytest.yield_fixture
def db_session():
# Set up SQLAlchemy to provide DB access
dsess = DoubleSession(zkmeta.Session, pymeta.Session)
# Clean up old sessions if they exist
dsess.remove()
engine = create_engine(ini.get("app:main", "sqlalchemy.url"))
# Drop all data to establish known state, mostly to prevent primary-key conflicts
engine.execute("drop schema if exists public cascade")
engine.execute("create schema public")
zkmeta.Base.metadata.create_all(engine)
dsess.configure(engine)
# Create basic config values, to allow basic pages to render
for key, val in base_general_config.iteritems():
ConfigFactory(key=key, value=val)
for key, val in base_rego_config.iteritems():
ConfigFactory(category='rego', key=key, value=val)
dsess.commit()
# Run the actual test
yield dsess
# No rollback, for functional tests we have to actually commit to DB
@pytest.yield_fixture
def smtplib():
Dummy_smtplib.install()
yield Dummy_smtplib
if Dummy_smtplib.existing:
Dummy_smtplib.existing.reset()<|fim▁end|> | |
<|file_name|>crypto.d.ts<|end_file_name|><|fim▁begin|>/**
* The `crypto` module provides cryptographic functionality that includes a set of
* wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
*
* ```js
* const { createHmac } = await import('crypto');
*
* const secret = 'abcdefg';
* const hash = createHmac('sha256', secret)
* .update('I love cupcakes')
* .digest('hex');
* console.log(hash);
* // Prints:
* // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/crypto.js)
*/
declare module 'crypto' {
import * as stream from 'node:stream';
import { PeerCertificate } from 'node:tls';
interface Certificate {
/**
* @deprecated
* @param spkac
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike): Buffer;
/**
* @deprecated
* @param spkac
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* @deprecated
* @param spkac
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
}
const Certificate: Certificate & {
/** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */
new (): Certificate;
/** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */
(): Certificate;
/**
* @param spkac
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike): Buffer;
/**
* @param spkac
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* @param spkac
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
};
namespace constants {
// https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants
const OPENSSL_VERSION_NUMBER: number;
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
const SSL_OP_ALL: number;
/** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
/** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
/** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */
const SSL_OP_CISCO_ANYCONNECT: number;
/** Instructs OpenSSL to turn on cookie exchange. */
const SSL_OP_COOKIE_EXCHANGE: number;
/** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
/** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
/** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */
const SSL_OP_EPHEMERAL_RSA: number;
/** Allows initial connection to servers that do not support RI. */
const SSL_OP_LEGACY_SERVER_CONNECT: number;
const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
const SSL_OP_MICROSOFT_SESS_ID_BUG: number;
/** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */
const SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
const SSL_OP_NETSCAPE_CA_DN_BUG: number;
const SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
/** Instructs OpenSSL to disable support for SSL/TLS compression. */
const SSL_OP_NO_COMPRESSION: number;
const SSL_OP_NO_QUERY_MTU: number;
/** Instructs OpenSSL to always start a new session when performing renegotiation. */
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
const SSL_OP_NO_SSLv2: number;
const SSL_OP_NO_SSLv3: number;
const SSL_OP_NO_TICKET: number;
const SSL_OP_NO_TLSv1: number;
const SSL_OP_NO_TLSv1_1: number;
const SSL_OP_NO_TLSv1_2: number;
const SSL_OP_PKCS1_CHECK_1: number;
const SSL_OP_PKCS1_CHECK_2: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */
const SSL_OP_SINGLE_DH_USE: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */
const SSL_OP_SINGLE_ECDH_USE: number;
const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
const SSL_OP_TLS_BLOCK_PADDING_BUG: number;
const SSL_OP_TLS_D5_BUG: number;
/** Instructs OpenSSL to disable version rollback attack detection. */
const SSL_OP_TLS_ROLLBACK_BUG: number;
const ENGINE_METHOD_RSA: number;
const ENGINE_METHOD_DSA: number;
const ENGINE_METHOD_DH: number;
const ENGINE_METHOD_RAND: number;
const ENGINE_METHOD_EC: number;
const ENGINE_METHOD_CIPHERS: number;
const ENGINE_METHOD_DIGESTS: number;
const ENGINE_METHOD_PKEY_METHS: number;
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
const ENGINE_METHOD_ALL: number;
const ENGINE_METHOD_NONE: number;
const DH_CHECK_P_NOT_SAFE_PRIME: number;
const DH_CHECK_P_NOT_PRIME: number;
const DH_UNABLE_TO_CHECK_GENERATOR: number;
const DH_NOT_SUITABLE_GENERATOR: number;
const ALPN_ENABLED: number;
const RSA_PKCS1_PADDING: number;
const RSA_SSLV23_PADDING: number;
const RSA_NO_PADDING: number;
const RSA_PKCS1_OAEP_PADDING: number;
const RSA_X931_PADDING: number;
const RSA_PKCS1_PSS_PADDING: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
const RSA_PSS_SALTLEN_DIGEST: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
const RSA_PSS_SALTLEN_MAX_SIGN: number;
/** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
const RSA_PSS_SALTLEN_AUTO: number;
const POINT_CONVERSION_COMPRESSED: number;
const POINT_CONVERSION_UNCOMPRESSED: number;
const POINT_CONVERSION_HYBRID: number;
/** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
const defaultCoreCipherList: string;
/** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
const defaultCipherList: string;
}
interface HashOptions extends stream.TransformOptions {
/**
* For XOF hash functions such as `shake256`, the
* outputLength option can be used to specify the desired output length in bytes.
*/
outputLength?: number | undefined;
}
/** @deprecated since v10.0.0 */
const fips: boolean;
/**
* Creates and returns a `Hash` object that can be used to generate hash digests
* using the given `algorithm`. Optional `options` argument controls stream
* behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
* can be used to specify the desired output length in bytes.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will
* display the available digest algorithms.
*
* Example: generating the sha256 sum of a file
*
* ```js
* import {
* createReadStream
* } from 'fs';
* import { argv } from 'process';
* const {
* createHash
* } = await import('crypto');
*
* const filename = argv[2];
*
* const hash = createHash('sha256');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hash.update(data);
* else {
* console.log(`${hash.digest('hex')} ${filename}`);
* }
* });
* ```
* @since v0.1.92
* @param options `stream.transform` options
*/
function createHash(algorithm: string, options?: HashOptions): Hash;
/**
* Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
* Optional `options` argument controls stream behavior.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will
* display the available digest algorithms.
*
* The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
* a `KeyObject`, its type must be `secret`.
*
* Example: generating the sha256 HMAC of a file
*
* ```js
* import {
* createReadStream
* } from 'fs';
* import { argv } from 'process';
* const {
* createHmac
* } = await import('crypto');
*
* const filename = argv[2];
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hmac.update(data);
* else {
* console.log(`${hmac.digest('hex')} ${filename}`);
* }
* });
* ```
* @since v0.1.94
* @param options `stream.transform` options
*/
function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac;
// https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex';
type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';
type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';
type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding;
type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid';
/**
* The `Hash` class is a utility for creating hash digests of data. It can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed hash digest on the readable side, or
* * Using the `hash.update()` and `hash.digest()` methods to produce the
* computed hash.
*
* The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hash` objects as streams:
*
* ```js
* const {
* createHash
* } = await import('crypto');
*
* const hash = createHash('sha256');
*
* hash.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hash.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* }
* });
*
* hash.write('some data to hash');
* hash.end();
* ```
*
* Example: Using `Hash` and piped streams:
*
* ```js
* import { createReadStream } from 'fs';
* import { stdout } from 'process';
* const { createHash } = await import('crypto');
*
* const hash = createHash('sha256');
*
* const input = createReadStream('test.js');
* input.pipe(hash).setEncoding('hex').pipe(stdout);
* ```
*
* Example: Using the `hash.update()` and `hash.digest()` methods:
*
* ```js
* const {
* createHash
* } = await import('crypto');
*
* const hash = createHash('sha256');
*
* hash.update('some data to hash');
* console.log(hash.digest('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* ```
* @since v0.1.92
*/
class Hash extends stream.Transform {
private constructor();
/**
* Creates a new `Hash` object that contains a deep copy of the internal state
* of the current `Hash` object.
*
* The optional `options` argument controls stream behavior. For XOF hash
* functions such as `'shake256'`, the `outputLength` option can be used to
* specify the desired output length in bytes.
*
* An error is thrown when an attempt is made to copy the `Hash` object after
* its `hash.digest()` method has been called.
*
* ```js
* // Calculate a rolling hash.
* const {
* createHash
* } = await import('crypto');
*
* const hash = createHash('sha256');
*
* hash.update('one');
* console.log(hash.copy().digest('hex'));
*
* hash.update('two');
* console.log(hash.copy().digest('hex'));
*
* hash.update('three');
* console.log(hash.copy().digest('hex'));
*
* // Etc.
* ```
* @since v13.1.0
* @param options `stream.transform` options
*/
copy(options?: stream.TransformOptions): Hash;
/**
* Updates the hash content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hash;
update(data: string, inputEncoding: Encoding): Hash;
/**
* Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
* If `encoding` is provided a string will be returned; otherwise
* a `Buffer` is returned.
*
* The `Hash` object can not be used again after `hash.digest()` method has been
* called. Multiple calls will cause an error to be thrown.
* @since v0.1.92
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
/**
* The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
* be used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed HMAC digest on the readable side, or
* * Using the `hmac.update()` and `hmac.digest()` methods to produce the
* computed HMAC digest.
*
* The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hmac` objects as streams:
*
* ```js
* const {
* createHmac
* } = await import('crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hmac.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* }
* });
*
* hmac.write('some data to hash');
* hmac.end();
* ```
*
* Example: Using `Hmac` and piped streams:
*
* ```js
* import { createReadStream } from 'fs';
* import { stdout } from 'process';
* const {
* createHmac
* } = await import('crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream('test.js');
* input.pipe(hmac).pipe(stdout);
* ```
*
* Example: Using the `hmac.update()` and `hmac.digest()` methods:
*
* ```js
* const {
* createHmac
* } = await import('crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.update('some data to hash');
* console.log(hmac.digest('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* ```
* @since v0.1.94
*/
class Hmac extends stream.Transform {
private constructor();
/**
* Updates the `Hmac` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.94
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hmac;
update(data: string, inputEncoding: Encoding): Hmac;
/**
* Calculates the HMAC digest of all of the data passed using `hmac.update()`.
* If `encoding` is
* provided a string is returned; otherwise a `Buffer` is returned;
*
* The `Hmac` object can not be used again after `hmac.digest()` has been
* called. Multiple calls to `hmac.digest()` will result in an error being thrown.
* @since v0.1.94
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
type KeyObjectType = 'secret' | 'public' | 'private';
interface KeyExportOptions<T extends KeyFormat> {
type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1';
format: T;
cipher?: string | undefined;
passphrase?: string | Buffer | undefined;
}
interface JwkKeyExportOptions {
format: 'jwk';
}
interface JsonWebKey {
crv?: string | undefined;
d?: string | undefined;
dp?: string | undefined;
dq?: string | undefined;
e?: string | undefined;
k?: string | undefined;
kty?: string | undefined;
n?: string | undefined;
p?: string | undefined;
q?: string | undefined;
qi?: string | undefined;
x?: string | undefined;
y?: string | undefined;
[key: string]: unknown;
}
interface AsymmetricKeyDetails {
/**
* Key size in bits (RSA, DSA).
*/
modulusLength?: number | undefined;
/**
* Public exponent (RSA).
*/
publicExponent?: bigint | undefined;
/**
* Name of the message digest (RSA-PSS).
*/
hashAlgorithm?: string | undefined;
/**
* Name of the message digest used by MGF1 (RSA-PSS).
*/
mgf1HashAlgorithm?: string | undefined;
/**
* Minimal salt length in bytes (RSA-PSS).
*/
saltLength?: number | undefined;
/**
* Size of q in bits (DSA).
*/
divisorLength?: number | undefined;
/**
* Name of the curve (EC).
*/
namedCurve?: string | undefined;
}
interface JwkKeyExportOptions {
format: 'jwk';
}
/**
* Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
* and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject`
* objects are not to be created directly using the `new`keyword.
*
* Most applications should consider using the new `KeyObject` API instead of
* passing keys as strings or `Buffer`s due to improved security features.
*
* `KeyObject` instances can be passed to other threads via `postMessage()`.
* The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
* be listed in the `transferList` argument.
* @since v11.6.0
*/
class KeyObject {
private constructor();
/**
* Example: Converting a `CryptoKey` instance to a `KeyObject`:
*
* ```js
* const { webcrypto, KeyObject } = await import('crypto');
* const { subtle } = webcrypto;
*
* const key = await subtle.generateKey({
* name: 'HMAC',
* hash: 'SHA-256',
* length: 256
* }, true, ['sign', 'verify']);
*
* const keyObject = KeyObject.from(key);
* console.log(keyObject.symmetricKeySize);
* // Prints: 32 (symmetric key size in bytes)
* ```
* @since v15.0.0
*/
static from(key: webcrypto.CryptoKey): KeyObject;
/**
* For asymmetric keys, this property represents the type of the key. Supported key
* types are:
*
* * `'rsa'` (OID 1.2.840.113549.1.1.1)
* * `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
* * `'dsa'` (OID 1.2.840.10040.4.1)
* * `'ec'` (OID 1.2.840.10045.2.1)
* * `'x25519'` (OID 1.3.101.110)
* * `'x448'` (OID 1.3.101.111)
* * `'ed25519'` (OID 1.3.101.112)
* * `'ed448'` (OID 1.3.101.113)
* * `'dh'` (OID 1.2.840.113549.1.3.1)
*
* This property is `undefined` for unrecognized `KeyObject` types and symmetric
* keys.
* @since v11.6.0
*/
asymmetricKeyType?: KeyType | undefined;
/**
* For asymmetric keys, this property represents the size of the embedded key in
* bytes. This property is `undefined` for symmetric keys.
*/
asymmetricKeySize?: number | undefined;
/**
* This property exists only on asymmetric keys. Depending on the type of the key,
* this object contains information about the key. None of the information obtained
* through this property can be used to uniquely identify a key or to compromise
* the security of the key.
*
* For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
* the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
* set.
*
* Other key details might be exposed via this API using additional attributes.
* @since v15.7.0
*/
asymmetricKeyDetails?: AsymmetricKeyDetails | undefined;
/**
* For symmetric keys, the following encoding options can be used:
*
* For public keys, the following encoding options can be used:
*
* For private keys, the following encoding options can be used:
*
* The result type depends on the selected encoding format, when PEM the
* result is a string, when DER it will be a buffer containing the data
* encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object.
*
* When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are
* ignored.
*
* PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
* the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be
* encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
* encrypted private keys. Since PKCS#8 defines its own
* encryption mechanism, PEM-level encryption is not supported when encrypting
* a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for
* PKCS#1 and SEC1 encryption.
* @since v11.6.0
*/
export(options: KeyExportOptions<'pem'>): string | Buffer;
export(options?: KeyExportOptions<'der'>): Buffer;
export(options?: JwkKeyExportOptions): JsonWebKey;
/**
* For secret keys, this property represents the size of the key in bytes. This
* property is `undefined` for asymmetric keys.
* @since v11.6.0
*/
symmetricKeySize?: number | undefined;
/**
* Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
* or `'private'` for private (asymmetric) keys.
* @since v11.6.0
*/
type: KeyObjectType;
}
type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305';
type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm';
type BinaryLike = string | NodeJS.ArrayBufferView;
type CipherKey = BinaryLike | KeyObject;
interface CipherCCMOptions extends stream.TransformOptions {
authTagLength: number;
}
interface CipherGCMOptions extends stream.TransformOptions {
authTagLength?: number | undefined;
}
/**
* Creates and returns a `Cipher` object that uses the given `algorithm` and`password`.
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will
* display the available cipher algorithms.
*
* The `password` is used to derive the cipher key and initialization vector (IV).
* The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`.
*
* The implementation of `crypto.createCipher()` derives keys using the OpenSSL
* function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
* iteration, and no salt. The lack of salt allows dictionary attacks as the same
* password always creates the same key. The low iteration count and
* non-cryptographically secure hash algorithm allow passwords to be tested very
* rapidly.
*
* In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that
* developers derive a key and IV on
* their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode
* (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
* they are used in order to avoid the risk of IV reuse that causes
* vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details.
* @since v0.1.94
* @deprecated Since v10.0.0 - Use {@link createCipheriv} instead.
* @param options `stream.transform` options
*/
function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher;
/**
* Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
* initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will
* display the available cipher algorithms.
*
* The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a
* given IV will be.
* @since v0.1.94
* @param options `stream.transform` options
*/
function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): CipherCCM;
function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): CipherGCM;
function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher;
/**
* Instances of the `Cipher` class are used to encrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain unencrypted
* data is written to produce encrypted data on the readable side, or
* * Using the `cipher.update()` and `cipher.final()` methods to produce
* the encrypted data.
*
* The {@link createCipher} or {@link createCipheriv} methods are
* used to create `Cipher` instances. `Cipher` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Cipher` objects as streams:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* // Once we have the key and iv, we can create and use the cipher...
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = '';
* cipher.setEncoding('hex');
*
* cipher.on('data', (chunk) => encrypted += chunk);
* cipher.on('end', () => console.log(encrypted));
*
* cipher.write('some clear text data');
* cipher.end();
* });
* });
* ```
*
* Example: Using `Cipher` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'fs';
*
* import {
* pipeline
* } from 'stream';
*
* const {
* scrypt,
* randomFill,
* createCipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.js');
* const output = createWriteStream('test.enc');
*
* pipeline(input, cipher, output, (err) => {
* if (err) throw err;
* });
* });
* });
* ```
*
* Example: Using the `cipher.update()` and `cipher.final()` methods:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
* encrypted += cipher.final('hex');
* console.log(encrypted);
* });
* });
* ```
* @since v0.1.94
*/
class Cipher extends stream.Transform {
private constructor();
/**
* Updates the cipher with `data`. If the `inputEncoding` argument is given,
* the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`,
* `TypedArray`, or `DataView`, then`inputEncoding` is ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
*
* The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being
* thrown.
* @since v0.1.94
* @param inputEncoding The `encoding` of the data.
* @param outputEncoding The `encoding` of the return value.
*/
update(data: BinaryLike): Buffer;
update(data: string, inputEncoding: Encoding): Buffer;
update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
/**
* Once the `cipher.final()` method has been called, the `Cipher` object can no
* longer be used to encrypt data. Attempts to call `cipher.final()` more than
* once will result in an error being thrown.
* @since v0.1.94
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): Buffer;
final(outputEncoding: BufferEncoding): string;
/**
* When using block encryption algorithms, the `Cipher` class will automatically
* add padding to the input data to the appropriate block size. To disable the
* default padding call `cipher.setAutoPadding(false)`.
*
* When `autoPadding` is `false`, the length of the entire input data must be a
* multiple of the cipher's block size or `cipher.final()` will throw an error.
* Disabling automatic padding is useful for non-standard padding, for instance
* using `0x0` instead of PKCS padding.
*
* The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
* @since v0.7.1
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(autoPadding?: boolean): this;
}
interface CipherCCM extends Cipher {
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
plaintextLength: number;
}
): this;
getAuthTag(): Buffer;
}
interface CipherGCM extends Cipher {
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
plaintextLength: number;
}
): this;
getAuthTag(): Buffer;
}
/**
* Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`.
*
* The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
* function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
* iteration, and no salt. The lack of salt allows dictionary attacks as the same
* password always creates the same key. The low iteration count and
* non-cryptographically secure hash algorithm allow passwords to be tested very
* rapidly.
*
* In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that
* developers derive a key and IV on
* their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object.
* @since v0.1.94
* @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead.
* @param options `stream.transform` options
*/
function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher;
/**
* Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags
* to those with the specified length.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will
* display the available cipher algorithms.
*
* The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a given
* IV will be.
* @since v0.1.94
* @param options `stream.transform` options
*/
function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): DecipherCCM;
function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): DecipherGCM;
function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher;
/**
* Instances of the `Decipher` class are used to decrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain encrypted
* data is written to produce unencrypted data on the readable side, or
* * Using the `decipher.update()` and `decipher.final()` methods to
* produce the unencrypted data.
*
* The {@link createDecipher} or {@link createDecipheriv} methods are
* used to create `Decipher` instances. `Decipher` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Decipher` objects as streams:
*
* ```js
* import { Buffer } from 'buffer';
* const {
* scryptSync,
* createDecipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Key length is dependent on the algorithm. In this case for aes192, it is
* // 24 bytes (192 bits).
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* let decrypted = '';
* decipher.on('readable', () => {
* while (null !== (chunk = decipher.read())) {
* decrypted += chunk.toString('utf8');
* }
* });
* decipher.on('end', () => {
* console.log(decrypted);
* // Prints: some clear text data
* });
*
* // Encrypted with same algorithm, key and iv.
* const encrypted =
* 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
* decipher.write(encrypted, 'hex');
* decipher.end();
* ```
*
* Example: Using `Decipher` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'fs';
* import { Buffer } from 'buffer';
* const {
* scryptSync,
* createDecipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.enc');
* const output = createWriteStream('test.js');
*
* input.pipe(decipher).pipe(output);
* ```
*
* Example: Using the `decipher.update()` and `decipher.final()` methods:
*
* ```js
* import { Buffer } from 'buffer';
* const {
* scryptSync,
* createDecipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* // Encrypted using same algorithm, key and iv.
* const encrypted =
* 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
* let decrypted = decipher.update(encrypted, 'hex', 'utf8');
* decrypted += decipher.final('utf8');
* console.log(decrypted);
* // Prints: some clear text data
* ```
* @since v0.1.94
*/
class Decipher extends stream.Transform {
private constructor();
/**
* Updates the decipher with `data`. If the `inputEncoding` argument is given,
* the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is
* ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
*
* The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error
* being thrown.
* @since v0.1.94
* @param inputEncoding The `encoding` of the `data` string.
* @param outputEncoding The `encoding` of the return value.
*/
update(data: NodeJS.ArrayBufferView): Buffer;
update(data: string, inputEncoding: Encoding): Buffer;
update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
/**
* Once the `decipher.final()` method has been called, the `Decipher` object can
* no longer be used to decrypt data. Attempts to call `decipher.final()` more
* than once will result in an error being thrown.
* @since v0.1.94
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): Buffer;
final(outputEncoding: BufferEncoding): string;
/**
* When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and
* removing padding.
*
* Turning auto padding off will only work if the input data's length is a
* multiple of the ciphers block size.
*
* The `decipher.setAutoPadding()` method must be called before `decipher.final()`.
* @since v0.7.1
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(auto_padding?: boolean): this;
}
interface DecipherCCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
plaintextLength: number;
}
): this;
}
interface DecipherGCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
plaintextLength: number;
}
): this;
}
interface PrivateKeyInput {
key: string | Buffer;
format?: KeyFormat | undefined;
type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined;
passphrase?: string | Buffer | undefined;
}
interface PublicKeyInput {
key: string | Buffer;
format?: KeyFormat | undefined;
type?: 'pkcs1' | 'spki' | undefined;
}
/**
* Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`.
*
* ```js
* const {
* generateKey
* } = await import('crypto');
*
* generateKey('hmac', { length: 64 }, (err, key) => {
* if (err) throw err;
* console.log(key.export().toString('hex')); // 46e..........620
* });
* ```
* @since v15.0.0
* @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
*/
function generateKey(
type: 'hmac' | 'aes',
options: {
length: number;
},
callback: (err: Error | null, key: KeyObject) => void
): void;
/**
* Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`.
*
* ```js
* const {
* generateKeySync
* } = await import('crypto');
*
* const key = generateKeySync('hmac', { length: 64 });
* console.log(key.export().toString('hex')); // e89..........41e
* ```
* @since v15.0.0
* @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
*/
function generateKeySync(
type: 'hmac' | 'aes',
options: {
length: number;
}
): KeyObject;
interface JsonWebKeyInput {
key: JsonWebKey;
format: 'jwk';
}
/**
* Creates and returns a new key object containing a private key. If `key` is a
* string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above.
*
* If the private key is encrypted, a `passphrase` must be specified. The length
* of the passphrase is limited to 1024 bytes.
* @since v11.6.0
*/
function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject;
/**
* Creates and returns a new key object containing a public key. If `key` is a
* string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key;
* otherwise, `key` must be an object with the properties described above.
*
* If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
*
* Because public keys can be derived from private keys, a private key may be
* passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the
* returned `KeyObject` will be `'public'` and that the private key cannot be
* extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned
* and it will be impossible to extract the private key from the returned object.
* @since v11.6.0
*/
function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject;
/**
* Creates and returns a new key object containing a secret key for symmetric
* encryption or `Hmac`.
* @since v11.6.0
* @param encoding The string encoding when `key` is a string.
*/
function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject;
function createSecretKey(key: string, encoding: BufferEncoding): KeyObject;
/**
* Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms.
* Optional `options` argument controls the `stream.Writable` behavior.
*
* In some cases, a `Sign` instance can be created using the name of a signature
* algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
* the corresponding digest algorithm. This does not work for all signature
* algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
* algorithm names.
* @since v0.1.92
* @param options `stream.Writable` options
*/
function createSign(algorithm: string, options?: stream.WritableOptions): Sign;
type DSAEncoding = 'der' | 'ieee-p1363';
interface SigningOptions {
/**
* @See crypto.constants.RSA_PKCS1_PADDING
*/
padding?: number | undefined;
saltLength?: number | undefined;
dsaEncoding?: DSAEncoding | undefined;
}
interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {}
interface SignKeyObjectInput extends SigningOptions {
key: KeyObject;
}
interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {}
interface VerifyKeyObjectInput extends SigningOptions {
key: KeyObject;
}
type KeyLike = string | Buffer | KeyObject;
/**
* The `Sign` class is a utility for generating signatures. It can be used in one
* of two ways:
*
* * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or
* * Using the `sign.update()` and `sign.sign()` methods to produce the
* signature.
*
* The {@link createSign} method is used to create `Sign` instances. The
* argument is the string name of the hash function to use. `Sign` objects are not
* to be created directly using the `new` keyword.
*
* Example: Using `Sign` and `Verify` objects as streams:
*
* ```js
* const {
* generateKeyPairSync,
* createSign,
* createVerify
* } = await import('crypto');
*
* const { privateKey, publicKey } = generateKeyPairSync('ec', {
* namedCurve: 'sect239k1'
* });
*
* const sign = createSign('SHA256');
* sign.write('some data to sign');
* sign.end();
* const signature = sign.sign(privateKey, 'hex');
*
* const verify = createVerify('SHA256');
* verify.write('some data to sign');
* verify.end();
* console.log(verify.verify(publicKey, signature, 'hex'));
* // Prints: true
* ```
*
* Example: Using the `sign.update()` and `verify.update()` methods:
*
* ```js
* const {
* generateKeyPairSync,
* createSign,
* createVerify
* } = await import('crypto');
*
* const { privateKey, publicKey } = generateKeyPairSync('rsa', {
* modulusLength: 2048,
* });
*
* const sign = createSign('SHA256');
* sign.update('some data to sign');
* sign.end();
* const signature = sign.sign(privateKey);
*
* const verify = createVerify('SHA256');
* verify.update('some data to sign');
* verify.end();
* console.log(verify.verify(publicKey, signature));
* // Prints: true
* ```
* @since v0.1.92
*/
class Sign extends stream.Writable {
private constructor();
/**
* Updates the `Sign` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): this;
update(data: string, inputEncoding: Encoding): this;
/**
* Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`.
*
* If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
* object, the following additional properties can be passed:
*
* If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned.
*
* The `Sign` object can not be again used after `sign.sign()` method has been
* called. Multiple calls to `sign.sign()` will result in an error being thrown.
* @since v0.1.92
*/
sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string;
}
/**
* Creates and returns a `Verify` object that uses the given algorithm.
* Use {@link getHashes} to obtain an array of names of the available
* signing algorithms. Optional `options` argument controls the`stream.Writable` behavior.
*
* In some cases, a `Verify` instance can be created using the name of a signature
* algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
* the corresponding digest algorithm. This does not work for all signature
* algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
* algorithm names.
* @since v0.1.92
* @param options `stream.Writable` options
*/
function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
/**
* The `Verify` class is a utility for verifying signatures. It can be used in one
* of two ways:
*
* * As a writable `stream` where written data is used to validate against the
* supplied signature, or
* * Using the `verify.update()` and `verify.verify()` methods to verify
* the signature.
*
* The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword.
*
* See `Sign` for examples.
* @since v0.1.92
*/
class Verify extends stream.Writable {
private constructor();
/**
* Updates the `Verify` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `inputEncoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Verify;
update(data: string, inputEncoding: Encoding): Verify;
/**
* Verifies the provided data using the given `object` and `signature`.
*
* If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an
* object, the following additional properties can be passed:
*
* The `signature` argument is the previously calculated signature for the data, in
* the `signatureEncoding`.
* If a `signatureEncoding` is specified, the `signature` is expected to be a
* string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* The `verify` object can not be used again after `verify.verify()` has been
* called. Multiple calls to `verify.verify()` will result in an error being
* thrown.
*
* Because public keys can be derived from private keys, a private key may
* be passed instead of a public key.
* @since v0.1.92
*/
verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean;
verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean;
}
/**
* Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
* optional specific `generator`.
*
* The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used.
*
* If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
* a `Buffer`, `TypedArray`, or `DataView` is expected.
*
* If `generatorEncoding` is specified, `generator` is expected to be a string;
* otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected.
* @since v0.11.12
* @param primeEncoding The `encoding` of the `prime` string.
* @param [generator=2]
* @param generatorEncoding The `encoding` of the `generator` string.
*/
function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman;
function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman;
/**
* The `DiffieHellman` class is a utility for creating Diffie-Hellman key
* exchanges.
*
* Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function.
*
* ```js
* import assert from 'assert';
*
* const {
* createDiffieHellman
* } = await import('crypto');
*
* // Generate Alice's keys...
* const alice = createDiffieHellman(2048);
* const aliceKey = alice.generateKeys();
*
* // Generate Bob's keys...
* const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
* const bobKey = bob.generateKeys();
*
* // Exchange and generate the secret...
* const aliceSecret = alice.computeSecret(bobKey);
* const bobSecret = bob.computeSecret(aliceKey);
*
* // OK
* assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
* ```
* @since v0.5.0
*/
class DiffieHellman {
private constructor();
/**
* Generates private and public Diffie-Hellman key values, and returns
* the public key in the specified `encoding`. This key should be
* transferred to the other party.
* If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
generateKeys(): Buffer;
generateKeys(encoding: BinaryToTextEncoding): string;
/**
* Computes the shared secret using `otherPublicKey` as the other
* party's public key and returns the computed shared secret. The supplied
* key is interpreted using the specified `inputEncoding`, and secret is
* encoded using specified `outputEncoding`.
* If the `inputEncoding` is not
* provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned.
* @since v0.5.0
* @param inputEncoding The `encoding` of an `otherPublicKey` string.
* @param outputEncoding The `encoding` of the return value.
*/
computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer;
computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer;
computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string;
computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman prime in the specified `encoding`.
* If `encoding` is provided a string is
* returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getPrime(): Buffer;
getPrime(encoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman generator in the specified `encoding`.
* If `encoding` is provided a string is
* returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getGenerator(): Buffer;
getGenerator(encoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman public key in the specified `encoding`.
* If `encoding` is provided a
* string is returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getPublicKey(): Buffer;
getPublicKey(encoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman private key in the specified `encoding`.
* If `encoding` is provided a
* string is returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getPrivateKey(): Buffer;
getPrivateKey(encoding: BinaryToTextEncoding): string;
/**
* Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected
* to be a string. If no `encoding` is provided, `publicKey` is expected
* to be a `Buffer`, `TypedArray`, or `DataView`.
* @since v0.5.0
* @param encoding The `encoding` of the `publicKey` string.
*/
setPublicKey(publicKey: NodeJS.ArrayBufferView): void;
setPublicKey(publicKey: string, encoding: BufferEncoding): void;
/**
* Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected
* to be a string. If no `encoding` is provided, `privateKey` is expected
* to be a `Buffer`, `TypedArray`, or `DataView`.
* @since v0.5.0
* @param encoding The `encoding` of the `privateKey` string.
*/
setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
setPrivateKey(privateKey: string, encoding: BufferEncoding): void;
/**
* A bit field containing any warnings and/or errors resulting from a check
* performed during initialization of the `DiffieHellman` object.
*
* The following values are valid for this property (as defined in `constants`module):
*
* * `DH_CHECK_P_NOT_SAFE_PRIME`
* * `DH_CHECK_P_NOT_PRIME`
* * `DH_UNABLE_TO_CHECK_GENERATOR`
* * `DH_NOT_SUITABLE_GENERATOR`
* @since v0.11.12
*/
verifyError: number;
}
/**
* Creates a predefined `DiffieHellmanGroup` key exchange object. The
* supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`,
* `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The
* returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing
* the keys (with `diffieHellman.setPublicKey()`, for example). The
* advantage of using this method is that the parties do not have to
* generate nor exchange a group modulus beforehand, saving both processor
* and communication time.
*
* Example (obtaining a shared secret):
*
* ```js
* const {
* getDiffieHellman
* } = await import('crypto');
* const alice = getDiffieHellman('modp14');
* const bob = getDiffieHellman('modp14');
*
* alice.generateKeys();
* bob.generateKeys();
*
* const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
* const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
*
* // aliceSecret and bobSecret should be the same
* console.log(aliceSecret === bobSecret);
* ```
* @since v0.7.5
*/
function getDiffieHellman(groupName: string): DiffieHellman;
/**
* Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
* implementation. A selected HMAC digest algorithm specified by `digest` is
* applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`.
*
* The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set;
* otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be
* thrown if any of the input arguments specify invalid values or types.
*
* If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
* please specify a `digest` explicitly.
*
* The `iterations` argument must be a number set as high as possible. The
* higher the number of iterations, the more secure the derived key will be,
* but will take a longer amount of time to complete.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* ```js
* const {
* pbkdf2
* } = await import('crypto');
*
* pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
* });
* ```
*
* The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been
* deprecated and use should be avoided.
*
* ```js
* import crypto from 'crypto';
* crypto.DEFAULT_ENCODING = 'hex';
* crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey); // '3745e48...aa39b34'
* });
* ```
*
* An array of supported digest functions can be retrieved using {@link getHashes}.
*
* This API uses libuv's threadpool, which can have surprising and
* negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
* @since v0.5.5
*/
function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void;
/**
* Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
* implementation. A selected HMAC digest algorithm specified by `digest` is
* applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`.
*
* If an error occurs an `Error` will be thrown, otherwise the derived key will be
* returned as a `Buffer`.
*
* If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
* please specify a `digest` explicitly.
*
* The `iterations` argument must be a number set as high as possible. The
* higher the number of iterations, the more secure the derived key will be,
* but will take a longer amount of time to complete.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* ```js
* const {
* pbkdf2Sync
* } = await import('crypto');
*
* const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
* console.log(key.toString('hex')); // '3745e48...08d59ae'
* ```
*
* The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use
* should be avoided.
*
* ```js
* import crypto from 'crypto';
* crypto.DEFAULT_ENCODING = 'hex';
* const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
* console.log(key); // '3745e48...aa39b34'
* ```
*
* An array of supported digest functions can be retrieved using {@link getHashes}.
* @since v0.9.3
*/
function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer;
/**
* Generates cryptographically strong pseudorandom data. The `size` argument
* is a number indicating the number of bytes to generate.
*
* If a `callback` function is provided, the bytes are generated asynchronously
* and the `callback` function is invoked with two arguments: `err` and `buf`.
* If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes.
*
* ```js
* // Asynchronous
* const {
* randomBytes
* } = await import('crypto');
*
* randomBytes(256, (err, buf) => {
* if (err) throw err;
* console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
* });
* ```
*
* If the `callback` function is not provided, the random bytes are generated
* synchronously and returned as a `Buffer`. An error will be thrown if
* there is a problem generating the bytes.
*
* ```js
* // Synchronous
* const {
* randomBytes
* } = await import('crypto');
*
* const buf = randomBytes(256);
* console.log(
* `${buf.length} bytes of random data: ${buf.toString('hex')}`);
* ```
*
* The `crypto.randomBytes()` method will not complete until there is
* sufficient entropy available.
* This should normally never take longer than a few milliseconds. The only time
* when generating the random bytes may conceivably block for a longer period of
* time is right after boot, when the whole system is still low on entropy.
*
* This API uses libuv's threadpool, which can have surprising and
* negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
*
* The asynchronous version of `crypto.randomBytes()` is carried out in a single
* threadpool request. To minimize threadpool task length variation, partition
* large `randomBytes` requests when doing so as part of fulfilling a client
* request.
* @since v0.5.8
* @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`.
* @return if the `callback` function is not provided.
*/
function randomBytes(size: number): Buffer;
function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function pseudoRandomBytes(size: number): Buffer;
function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
/**
* Return a random integer `n` such that `min <= n < max`. This
* implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias).
*
* The range (`max - min`) must be less than 248. `min` and `max` must
* be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
*
* If the `callback` function is not provided, the random integer is
* generated synchronously.
*
* ```js
* // Asynchronous
* const {
* randomInt
* } = await import('crypto');
*
* randomInt(3, (err, n) => {
* if (err) throw err;
* console.log(`Random number chosen from (0, 1, 2): ${n}`);
* });
* ```
*
* ```js
* // Synchronous
* const {
* randomInt
* } = await import('crypto');
*
* const n = randomInt(3);
* console.log(`Random number chosen from (0, 1, 2): ${n}`);
* ```
*
* ```js
* // With `min` argument
* const {
* randomInt
* } = await import('crypto');
*
* const n = randomInt(1, 7);
* console.log(`The dice rolled: ${n}`);
* ```
* @since v14.10.0, v12.19.0
* @param [min=0] Start of random range (inclusive).
* @param max End of random range (exclusive).
* @param callback `function(err, n) {}`.
*/
function randomInt(max: number): number;
function randomInt(min: number, max: number): number;
function randomInt(max: number, callback: (err: Error | null, value: number) => void): void;
function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
/**
* Synchronous version of {@link randomFill}.
*
* ```js
* import { Buffer } from 'buffer';
* const { randomFillSync } = await import('crypto');
*
* const buf = Buffer.alloc(10);
* console.log(randomFillSync(buf).toString('hex'));
*
* randomFillSync(buf, 5);
* console.log(buf.toString('hex'));
*
* // The above is equivalent to the following:
* randomFillSync(buf, 5, 5);
* console.log(buf.toString('hex'));
* ```
*
* Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`.
*
* ```js
* import { Buffer } from 'buffer';
* const { randomFillSync } = await import('crypto');
*
* const a = new Uint32Array(10);
* console.log(Buffer.from(randomFillSync(a).buffer,
* a.byteOffset, a.byteLength).toString('hex'));
*
* const b = new DataView(new ArrayBuffer(10));
* console.log(Buffer.from(randomFillSync(b).buffer,
* b.byteOffset, b.byteLength).toString('hex'));
*
* const c = new ArrayBuffer(10);
* console.log(Buffer.from(randomFillSync(c)).toString('hex'));
* ```
* @since v7.10.0, v6.13.0
* @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
* @param [offset=0]
* @param [size=buffer.length - offset]
* @return The object passed as `buffer` argument.
*/
function randomFillSync<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
/**
* This function is similar to {@link randomBytes} but requires the first
* argument to be a `Buffer` that will be filled. It also
* requires that a callback is passed in.
*
* If the `callback` function is not provided, an error will be thrown.
*
* ```js
* import { Buffer } from 'buffer';
* const { randomFill } = await import('crypto');
*
* const buf = Buffer.alloc(10);
* randomFill(buf, (err, buf) => {
* if (err) throw err;
* console.log(buf.toString('hex'));
* });
*
* randomFill(buf, 5, (err, buf) => {
* if (err) throw err;
* console.log(buf.toString('hex'));
* });
*
* // The above is equivalent to the following:
* randomFill(buf, 5, 5, (err, buf) => {
* if (err) throw err;
* console.log(buf.toString('hex'));
* });
* ```
*
* Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`.
*
* While this includes instances of `Float32Array` and `Float64Array`, this
* function should not be used to generate random floating-point numbers. The
* result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
* contains finite numbers only, they are not drawn from a uniform random
* distribution and have no meaningful lower or upper bounds.
*
* ```js
* import { Buffer } from 'buffer';
* const { randomFill } = await import('crypto');
*
* const a = new Uint32Array(10);
* randomFill(a, (err, buf) => {
* if (err) throw err;
* console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
* .toString('hex'));
* });
*
* const b = new DataView(new ArrayBuffer(10));
* randomFill(b, (err, buf) => {
* if (err) throw err;
* console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
* .toString('hex'));
* });
*
* const c = new ArrayBuffer(10);
* randomFill(c, (err, buf) => {
* if (err) throw err;
* console.log(Buffer.from(buf).toString('hex'));
* });
* ```
*
* This API uses libuv's threadpool, which can have surprising and
* negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
*
* The asynchronous version of `crypto.randomFill()` is carried out in a single
* threadpool request. To minimize threadpool task length variation, partition
* large `randomFill` requests when doing so as part of fulfilling a client
* request.
* @since v7.10.0, v6.13.0
* @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
* @param [offset=0]
* @param [size=buffer.length - offset]
* @param callback `function(err, buf) {}`.
*/
function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, callback: (err: Error | null, buf: T) => void): void;
function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void;
function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void;
interface ScryptOptions {
cost?: number | undefined;
blockSize?: number | undefined;
parallelization?: number | undefined;
N?: number | undefined;
r?: number | undefined;
p?: number | undefined;
maxmem?: number | undefined;
}
/**
* Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
* key derivation function that is designed to be expensive computationally and
* memory-wise in order to make brute-force attacks unrewarding.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the
* callback as a `Buffer`.
*
* An exception is thrown when any of the input arguments specify invalid values
* or types.
*
* ```js
* const {
* scrypt
* } = await import('crypto');
*
* // Using the factory defaults.
* scrypt('password', 'salt', 64, (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
* });
* // Using a custom N parameter. Must be a power of two.
* scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
* });
* ```
* @since v10.5.0
*/
function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void;
function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void;
/**
* Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
* key derivation function that is designed to be expensive computationally and
* memory-wise in order to make brute-force attacks unrewarding.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* An exception is thrown when key derivation fails, otherwise the derived key is
* returned as a `Buffer`.
*
* An exception is thrown when any of the input arguments specify invalid values
* or types.
*
* ```js
* const {
* scryptSync
* } = await import('crypto');
* // Using the factory defaults.
*
* const key1 = scryptSync('password', 'salt', 64);
* console.log(key1.toString('hex')); // '3745e48...08d59ae'
* // Using a custom N parameter. Must be a power of two.
* const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
* console.log(key2.toString('hex')); // '3745e48...aa39b34'
* ```
* @since v10.5.0
*/
function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
interface RsaPublicKey {
key: KeyLike;
padding?: number | undefined;
}
interface RsaPrivateKey {
key: KeyLike;
passphrase?: string | undefined;
/**
* @default 'sha1'
*/
oaepHash?: string | undefined;
oaepLabel?: NodeJS.TypedArray | undefined;
padding?: number | undefined;
}
/**
* Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using
* the corresponding private key, for example using {@link privateDecrypt}.
*
* If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`.
*
* Because RSA public keys can be derived from private keys, a private key may
* be passed instead of a public key.
* @since v0.11.14
*/
function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* Decrypts `buffer` with `key`.`buffer` was previously encrypted using
* the corresponding private key, for example using {@link privateEncrypt}.
*
* If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`.
*
* Because RSA public keys can be derived from private keys, a private key may
* be passed instead of a public key.
* @since v1.1.0
*/
function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
* the corresponding public key, for example using {@link publicEncrypt}.
*
* If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`.
* @since v0.11.14
*/
function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
* the corresponding public key, for example using {@link publicDecrypt}.
*
* If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`.
* @since v1.1.0
*/
function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* ```js
* const {
* getCiphers
* } = await import('crypto');
*
* console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
* ```
* @since v0.9.3
* @return An array with the names of the supported cipher algorithms.
*/
function getCiphers(): string[];
/**
* ```js
* const {
* getCurves
* } = await import('crypto');
*
* console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
* ```
* @since v2.3.0
* @return An array with the names of the supported elliptic curves.
*/
function getCurves(): string[];
/**
* @since v10.0.0
* @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.
*/
function getFips(): 1 | 0;
/**
* ```js
* const {
* getHashes
* } = await import('crypto');
*
* console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
* ```
* @since v0.9.3
* @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
*/
function getHashes(): string[];
/**
* The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
* key exchanges.
*
* Instances of the `ECDH` class can be created using the {@link createECDH} function.
*
* ```js
* import assert from 'assert';
*
* const {
* createECDH
* } = await import('crypto');
*
* // Generate Alice's keys...
* const alice = createECDH('secp521r1');
* const aliceKey = alice.generateKeys();
*
* // Generate Bob's keys...
* const bob = createECDH('secp521r1');
* const bobKey = bob.generateKeys();
*
* // Exchange and generate the secret...
* const aliceSecret = alice.computeSecret(bobKey);
* const bobSecret = bob.computeSecret(aliceKey);
*
* assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
* // OK
* ```
* @since v0.11.14
*/
class ECDH {
private constructor();
/**
* Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
* format specified by `format`. The `format` argument specifies point encoding
* and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is
* interpreted using the specified `inputEncoding`, and the returned key is encoded
* using the specified `outputEncoding`.
*
* Use {@link getCurves} to obtain a list of available curve names.
* On recent OpenSSL releases, `openssl ecparam -list_curves` will also display
* the name and description of each available elliptic curve.
*
* If `format` is not specified the point will be returned in `'uncompressed'`format.
*
* If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* Example (uncompressing a key):
*
* ```js
* const {
* createECDH,
* ECDH
* } = await import('crypto');
*
* const ecdh = createECDH('secp256k1');
* ecdh.generateKeys();
*
* const compressedKey = ecdh.getPublicKey('hex', 'compressed');
*
* const uncompressedKey = ECDH.convertKey(compressedKey,
* 'secp256k1',
* 'hex',
* 'hex',
* 'uncompressed');
*
* // The converted key and the uncompressed public key should be the same
* console.log(uncompressedKey === ecdh.getPublicKey('hex'));
* ```
* @since v10.0.0
* @param inputEncoding The `encoding` of the `key` string.
* @param outputEncoding The `encoding` of the return value.
* @param [format='uncompressed']
*/
static convertKey(
key: BinaryLike,
curve: string,
inputEncoding?: BinaryToTextEncoding,
outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url',
format?: 'uncompressed' | 'compressed' | 'hybrid'
): Buffer | string;
/**
* Generates private and public EC Diffie-Hellman key values, and returns
* the public key in the specified `format` and `encoding`. This key should be
* transferred to the other party.
*
* The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format.
*
* If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
* @since v0.11.14<|fim▁hole|> * @param encoding The `encoding` of the return value.
* @param [format='uncompressed']
*/
generateKeys(): Buffer;
generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
/**
* Computes the shared secret using `otherPublicKey` as the other
* party's public key and returns the computed shared secret. The supplied
* key is interpreted using specified `inputEncoding`, and the returned secret
* is encoded using the specified `outputEncoding`.
* If the `inputEncoding` is not
* provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`.
*
* If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned.
*
* `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is
* usually supplied from a remote user over an insecure network,
* be sure to handle this exception accordingly.
* @since v0.11.14
* @param inputEncoding The `encoding` of the `otherPublicKey` string.
* @param outputEncoding The `encoding` of the return value.
*/
computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer;
computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer;
computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string;
computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string;
/**
* If `encoding` is specified, a string is returned; otherwise a `Buffer` is
* returned.
* @since v0.11.14
* @param encoding The `encoding` of the return value.
* @return The EC Diffie-Hellman in the specified `encoding`.
*/
getPrivateKey(): Buffer;
getPrivateKey(encoding: BinaryToTextEncoding): string;
/**
* The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format.
*
* If `encoding` is specified, a string is returned; otherwise a `Buffer` is
* returned.
* @since v0.11.14
* @param encoding The `encoding` of the return value.
* @param [format='uncompressed']
* @return The EC Diffie-Hellman public key in the specified `encoding` and `format`.
*/
getPublicKey(): Buffer;
getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
/**
* Sets the EC Diffie-Hellman private key.
* If `encoding` is provided, `privateKey` is expected
* to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* If `privateKey` is not valid for the curve specified when the `ECDH` object was
* created, an error is thrown. Upon setting the private key, the associated
* public point (key) is also generated and set in the `ECDH` object.
* @since v0.11.14
* @param encoding The `encoding` of the `privateKey` string.
*/
setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void;
}
/**
* Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
* predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent
* OpenSSL releases, `openssl ecparam -list_curves` will also display the name
* and description of each available elliptic curve.
* @since v0.11.14
*/
function createECDH(curveName: string): ECDH;
/**
* This function is based on a constant-time algorithm.
* Returns true if `a` is equal to `b`, without leaking timing information that
* would allow an attacker to guess one of the values. This is suitable for
* comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/).
*
* `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
* must have the same byte length.
*
* If at least one of `a` and `b` is a `TypedArray` with more than one byte per
* entry, such as `Uint16Array`, the result will be computed using the platform
* byte order.
*
* Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code
* is timing-safe. Care should be taken to ensure that the surrounding code does
* not introduce timing vulnerabilities.
* @since v6.6.0
*/
function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean;
/** @deprecated since v10.0.0 */
const DEFAULT_ENCODING: BufferEncoding;
type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448';
type KeyFormat = 'pem' | 'der';
interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
format: T;
cipher?: string | undefined;
passphrase?: string | undefined;
}
interface KeyPairKeyObjectResult {
publicKey: KeyObject;
privateKey: KeyObject;
}
interface ED25519KeyPairKeyObjectOptions {}
interface ED448KeyPairKeyObjectOptions {}
interface X25519KeyPairKeyObjectOptions {}
interface X448KeyPairKeyObjectOptions {}
interface ECKeyPairKeyObjectOptions {
/**
* Name of the curve to use
*/
namedCurve: string;
}
interface RSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
}
interface RSAPSSKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
/**
* Name of the message digest
*/
hashAlgorithm?: string;
/**
* Name of the message digest used by MGF1
*/
mgf1HashAlgorithm?: string;
/**
* Minimal salt length in bytes
*/
saltLength?: string;
}
interface DSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
}
interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs1' | 'pkcs8';
};
}
interface RSAPSSKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
/**
* Name of the message digest
*/
hashAlgorithm?: string;
/**
* Name of the message digest used by MGF1
*/
mgf1HashAlgorithm?: string;
/**
* Minimal salt length in bytes
*/
saltLength?: string;
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Name of the curve to use.
*/
namedCurve: string;
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'sec1' | 'pkcs8';
};
}
interface ED25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface ED448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface X25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface X448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
publicKey: T1;
privateKey: T2;
}
/**
* Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
* Ed25519, Ed448, X25519, X448, and DH are currently supported.
*
* If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
* behaves as if `keyObject.export()` had been called on its result. Otherwise,
* the respective part of the key is returned as a `KeyObject`.
*
* When encoding public keys, it is recommended to use `'spki'`. When encoding
* private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
* and to keep the passphrase confidential.
*
* ```js
* const {
* generateKeyPairSync
* } = await import('crypto');
*
* const {
* publicKey,
* privateKey,
* } = generateKeyPairSync('rsa', {
* modulusLength: 4096,
* publicKeyEncoding: {
* type: 'spki',
* format: 'pem'
* },
* privateKeyEncoding: {
* type: 'pkcs8',
* format: 'pem',
* cipher: 'aes-256-cbc',
* passphrase: 'top secret'
* }
* });
* ```
*
* The return value `{ publicKey, privateKey }` represents the generated key pair.
* When PEM encoding was selected, the respective key will be a string, otherwise
* it will be a buffer containing the data encoded as DER.
* @since v10.12.0
* @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
*/
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
/**
* Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
* Ed25519, Ed448, X25519, X448, and DH are currently supported.
*
* If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
* behaves as if `keyObject.export()` had been called on its result. Otherwise,
* the respective part of the key is returned as a `KeyObject`.
*
* It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage:
*
* ```js
* const {
* generateKeyPair
* } = await import('crypto');
*
* generateKeyPair('rsa', {
* modulusLength: 4096,
* publicKeyEncoding: {
* type: 'spki',
* format: 'pem'
* },
* privateKeyEncoding: {
* type: 'pkcs8',
* format: 'pem',
* cipher: 'aes-256-cbc',
* passphrase: 'top secret'
* }
* }, (err, publicKey, privateKey) => {
* // Handle errors and use the generated key pair.
* });
* ```
*
* On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair.
*
* If this method is invoked as its `util.promisify()` ed version, it returns
* a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
* @since v10.12.0
* @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
*/
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
namespace generateKeyPair {
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'rsa-pss',
options: RSAPSSKeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'rsa-pss',
options: RSAPSSKeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'rsa-pss',
options: RSAPSSKeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'rsa-pss',
options: RSAPSSKeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'pem', 'pem'>
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'pem', 'der'>
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'der', 'pem'>
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'der', 'der'>
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
}
/**
* Calculates and returns the signature for `data` using the given private key and
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
* dependent upon the key type (especially Ed25519 and Ed448).
*
* If `key` is not a `KeyObject`, this function behaves as if `key` had been
* passed to {@link createPrivateKey}. If it is an object, the following
* additional properties can be passed:
*
* If the `callback` function is provided this function uses libuv's threadpool.
* @since v12.0.0
*/
function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
function sign(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
callback: (error: Error | null, data: Buffer) => void
): void;
/**
* Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
* key type (especially Ed25519 and Ed448).
*
* If `key` is not a `KeyObject`, this function behaves as if `key` had been
* passed to {@link createPublicKey}. If it is an object, the following
* additional properties can be passed:
*
* The `signature` argument is the previously calculated signature for the `data`.
*
* Because public keys can be derived from private keys, a private key or a public
* key may be passed for `key`.
*
* If the `callback` function is provided this function uses libuv's threadpool.
* @since v12.0.0
*/
function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean;
function verify(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
signature: NodeJS.ArrayBufferView,
callback: (error: Error | null, result: boolean) => void
): void;
/**
* Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
* Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
* @since v13.9.0, v12.17.0
*/
function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer;
type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts';
interface CipherInfoOptions {
/**
* A test key length.
*/
keyLength?: number | undefined;
/**
* A test IV length.
*/
ivLength?: number | undefined;
}
interface CipherInfo {
/**
* The name of the cipher.
*/
name: string;
/**
* The nid of the cipher.
*/
nid: number;
/**
* The block size of the cipher in bytes.
* This property is omitted when mode is 'stream'.
*/
blockSize?: number | undefined;
/**
* The expected or default initialization vector length in bytes.
* This property is omitted if the cipher does not use an initialization vector.
*/
ivLength?: number | undefined;
/**
* The expected or default key length in bytes.
*/
keyLength: number;
/**
* The cipher mode.
*/
mode: CipherMode;
}
/**
* Returns information about a given cipher.
*
* Some ciphers accept variable length keys and initialization vectors. By default,
* the `crypto.getCipherInfo()` method will return the default values for these
* ciphers. To test if a given key length or iv length is acceptable for given
* cipher, use the `keyLength` and `ivLength` options. If the given values are
* unacceptable, `undefined` will be returned.
* @since v15.0.0
* @param nameOrNid The name or nid of the cipher to query.
*/
function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined;
/**
* HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
*
* The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set;
* otherwise `err` will be `null`. The successfully generated `derivedKey` will
* be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
* of the input arguments specify invalid values or types.
*
* ```js
* import { Buffer } from 'buffer';
* const {
* hkdf
* } = await import('crypto');
*
* hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
* if (err) throw err;
* console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
* });
* ```
* @since v15.0.0
* @param digest The digest algorithm to use.
* @param ikm The input keying material. It must be at least one byte in length.
* @param salt The salt value. Must be provided but can be zero-length.
* @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
* @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
* generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
*/
function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void;
/**
* Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The
* given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes.
*
* The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
*
* An error will be thrown if any of the input arguments specify invalid values or
* types, or if the derived key cannot be generated.
*
* ```js
* import { Buffer } from 'buffer';
* const {
* hkdfSync
* } = await import('crypto');
*
* const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
* console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
* ```
* @since v15.0.0
* @param digest The digest algorithm to use.
* @param ikm The input keying material. It must be at least one byte in length.
* @param salt The salt value. Must be provided but can be zero-length.
* @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
* @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
* generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
*/
function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer;
interface SecureHeapUsage {
/**
* The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.
*/
total: number;
/**
* The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.
*/
min: number;
/**
* The total number of bytes currently allocated from the secure heap.
*/
used: number;
/**
* The calculated ratio of `used` to `total` allocated bytes.
*/
utilization: number;
}
/**
* @since v15.6.0
*/
function secureHeapUsed(): SecureHeapUsage;
interface RandomUUIDOptions {
/**
* By default, to improve performance,
* Node.js will pre-emptively generate and persistently cache enough
* random data to generate up to 128 random UUIDs. To generate a UUID
* without using the cache, set `disableEntropyCache` to `true`.
*
* @default `false`
*/
disableEntropyCache?: boolean | undefined;
}
/**
* Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a
* cryptographic pseudorandom number generator.
* @since v15.6.0
*/
function randomUUID(options?: RandomUUIDOptions): string;
interface X509CheckOptions {
/**
* @default 'always'
*/
subject: 'always' | 'never';
/**
* @default true
*/
wildcards: boolean;
/**
* @default true
*/
partialWildcards: boolean;
/**
* @default false
*/
multiLabelWildcards: boolean;
/**
* @default false
*/
singleLabelSubdomains: boolean;
}
/**
* Encapsulates an X509 certificate and provides read-only access to
* its information.
*
* ```js
* const { X509Certificate } = await import('crypto');
*
* const x509 = new X509Certificate('{... pem encoded cert ...}');
*
* console.log(x509.subject);
* ```
* @since v15.6.0
*/
class X509Certificate {
/**
* Will be \`true\` if this is a Certificate Authority (ca) certificate.
* @since v15.6.0
*/
readonly ca: boolean;
/**
* The SHA-1 fingerprint of this certificate.
* @since v15.6.0
*/
readonly fingerprint: string;
/**
* The SHA-256 fingerprint of this certificate.
* @since v15.6.0
*/
readonly fingerprint256: string;
/**
* The complete subject of this certificate.
* @since v15.6.0
*/
readonly subject: string;
/**
* The subject alternative name specified for this certificate.
* @since v15.6.0
*/
readonly subjectAltName: string;
/**
* The information access content of this certificate.
* @since v15.6.0
*/
readonly infoAccess: string;
/**
* An array detailing the key usages for this certificate.
* @since v15.6.0
*/
readonly keyUsage: string[];
/**
* The issuer identification included in this certificate.
* @since v15.6.0
*/
readonly issuer: string;
/**
* The issuer certificate or `undefined` if the issuer certificate is not
* available.
* @since v15.9.0
*/
readonly issuerCertificate?: X509Certificate | undefined;
/**
* The public key `KeyObject` for this certificate.
* @since v15.6.0
*/
readonly publicKey: KeyObject;
/**
* A `Buffer` containing the DER encoding of this certificate.
* @since v15.6.0
*/
readonly raw: Buffer;
/**
* The serial number of this certificate.
* @since v15.6.0
*/
readonly serialNumber: string;
/**
* The date/time from which this certificate is considered valid.
* @since v15.6.0
*/
readonly validFrom: string;
/**
* The date/time until which this certificate is considered valid.
* @since v15.6.0
*/
readonly validTo: string;
constructor(buffer: BinaryLike);
/**
* Checks whether the certificate matches the given email address.
* @since v15.6.0
* @return Returns `email` if the certificate matches, `undefined` if it does not.
*/
checkEmail(email: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether the certificate matches the given host name.
* @since v15.6.0
* @return Returns `name` if the certificate matches, `undefined` if it does not.
*/
checkHost(name: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether the certificate matches the given IP address (IPv4 or IPv6).
* @since v15.6.0
* @return Returns `ip` if the certificate matches, `undefined` if it does not.
*/
checkIP(ip: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether this certificate was issued by the given `otherCert`.
* @since v15.6.0
*/
checkIssued(otherCert: X509Certificate): boolean;
/**
* Checks whether the public key for this certificate is consistent with
* the given private key.
* @since v15.6.0
* @param privateKey A private key.
*/
checkPrivateKey(privateKey: KeyObject): boolean;
/**
* There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded
* certificate.
* @since v15.6.0
*/
toJSON(): string;
/**
* Returns information about this certificate using the legacy `certificate object` encoding.
* @since v15.6.0
*/
toLegacyObject(): PeerCertificate;
/**
* Returns the PEM-encoded certificate.
* @since v15.6.0
*/
toString(): string;
/**
* Verifies that this certificate was signed by the given public key.
* Does not perform any other validation checks on the certificate.
* @since v15.6.0
* @param publicKey A public key.
*/
verify(publicKey: KeyObject): boolean;
}
type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint;
interface GeneratePrimeOptions {
add?: LargeNumberLike | undefined;
rem?: LargeNumberLike | undefined;
/**
* @default false
*/
safe?: boolean | undefined;
bigint?: boolean | undefined;
}
interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions {
bigint: true;
}
interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions {
bigint?: false | undefined;
}
/**
* Generates a pseudorandom prime of `size` bits.
*
* If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime.
*
* The `options.add` and `options.rem` parameters can be used to enforce additional
* requirements, e.g., for Diffie-Hellman:
*
* * If `options.add` and `options.rem` are both set, the prime will satisfy the
* condition that `prime % add = rem`.
* * If only `options.add` is set and `options.safe` is not `true`, the prime will
* satisfy the condition that `prime % add = 1`.
* * If only `options.add` is set and `options.safe` is set to `true`, the prime
* will instead satisfy the condition that `prime % add = 3`. This is necessary
* because `prime % add = 1` for `options.add > 2` would contradict the condition
* enforced by `options.safe`.
* * `options.rem` is ignored if `options.add` is not given.
*
* Both `options.add` and `options.rem` must be encoded as big-endian sequences
* if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`.
*
* By default, the prime is encoded as a big-endian sequence of octets
* in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
* @since v15.8.0
* @param size The size (in bits) of the prime to generate.
*/
function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void;
function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void;
/**
* Generates a pseudorandom prime of `size` bits.
*
* If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime.
*
* The `options.add` and `options.rem` parameters can be used to enforce additional
* requirements, e.g., for Diffie-Hellman:
*
* * If `options.add` and `options.rem` are both set, the prime will satisfy the
* condition that `prime % add = rem`.
* * If only `options.add` is set and `options.safe` is not `true`, the prime will
* satisfy the condition that `prime % add = 1`.
* * If only `options.add` is set and `options.safe` is set to `true`, the prime
* will instead satisfy the condition that `prime % add = 3`. This is necessary
* because `prime % add = 1` for `options.add > 2` would contradict the condition
* enforced by `options.safe`.
* * `options.rem` is ignored if `options.add` is not given.
*
* Both `options.add` and `options.rem` must be encoded as big-endian sequences
* if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`.
*
* By default, the prime is encoded as a big-endian sequence of octets
* in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
* @since v15.8.0
* @param size The size (in bits) of the prime to generate.
*/
function generatePrimeSync(size: number): ArrayBuffer;
function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint;
function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer;
function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint;
interface CheckPrimeOptions {
/**
* The number of Miller-Rabin probabilistic primality iterations to perform.
* When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input.
* Care must be used when selecting a number of checks.
* Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details.
*
* @default 0
*/
checks?: number | undefined;
}
/**
* Checks the primality of the `candidate`.
* @since v15.8.0
* @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
*/
function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void;
function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void;
/**
* Checks the primality of the `candidate`.
* @since v15.8.0
* @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
* @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.
*/
function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean;
namespace webcrypto {
class CryptoKey {} // placeholder
}
}
declare module 'node:crypto' {
export * from 'crypto';
}<|fim▁end|> | |
<|file_name|>request.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ReferrerPolicy;
use hyper::header::Headers;
use hyper::method::Method;
use msg::constellation_msg::PipelineId;
use servo_url::{ImmutableOrigin, ServoUrl};
use std::default::Default;
/// An [initiator](https://fetch.spec.whatwg.org/#concept-request-initiator)
#[derive(Copy, Clone, PartialEq, HeapSizeOf)]
pub enum Initiator {
None,
Download,
ImageSet,
Manifest,
XSLT,
}
/// A request [type](https://fetch.spec.whatwg.org/#concept-request-type)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum Type {
None,
Audio,
Font,
Image,
Script,
Style,
Track,
Video,
}
<|fim▁hole|>#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum Destination {
None,
Document,
Embed,
Font,
Image,
Manifest,
Media,
Object,
Report,
Script,
ServiceWorker,
SharedWorker,
Style,
Worker,
XSLT,
}
/// A request [origin](https://fetch.spec.whatwg.org/#concept-request-origin)
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, HeapSizeOf)]
pub enum Origin {
Client,
Origin(ImmutableOrigin),
}
/// A [referer](https://fetch.spec.whatwg.org/#concept-request-referrer)
#[derive(Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum Referrer {
NoReferrer,
/// Default referrer if nothing is specified
Client,
ReferrerUrl(ServoUrl),
}
/// A [request mode](https://fetch.spec.whatwg.org/#concept-request-mode)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum RequestMode {
Navigate,
SameOrigin,
NoCors,
CorsMode,
WebSocket
}
/// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum CredentialsMode {
Omit,
CredentialsSameOrigin,
Include,
}
/// [Cache mode](https://fetch.spec.whatwg.org/#concept-request-cache-mode)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum CacheMode {
Default,
NoStore,
Reload,
NoCache,
ForceCache,
OnlyIfCached,
}
/// [Service-workers mode](https://fetch.spec.whatwg.org/#request-service-workers-mode)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum ServiceWorkersMode {
All,
Foreign,
None,
}
/// [Redirect mode](https://fetch.spec.whatwg.org/#concept-request-redirect-mode)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)]
pub enum RedirectMode {
Follow,
Error,
Manual,
}
/// [Response tainting](https://fetch.spec.whatwg.org/#concept-request-response-tainting)
#[derive(Copy, Clone, PartialEq, HeapSizeOf)]
pub enum ResponseTainting {
Basic,
CorsTainting,
Opaque,
}
/// [Window](https://fetch.spec.whatwg.org/#concept-request-window)
#[derive(Copy, Clone, PartialEq, HeapSizeOf)]
pub enum Window {
NoWindow,
Client, // TODO: Environmental settings object
}
/// [CORS settings attribute](https://html.spec.whatwg.org/multipage/#attr-crossorigin-anonymous)
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize)]
pub enum CorsSettings {
Anonymous,
UseCredentials,
}
#[derive(Serialize, Deserialize, Clone, HeapSizeOf)]
pub struct RequestInit {
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
#[ignore_heap_size_of = "Defined in hyper"]
pub method: Method,
pub url: ServoUrl,
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
#[ignore_heap_size_of = "Defined in hyper"]
pub headers: Headers,
pub unsafe_request: bool,
pub body: Option<Vec<u8>>,
pub service_workers_mode: ServiceWorkersMode,
// TODO: client object
pub type_: Type,
pub destination: Destination,
pub synchronous: bool,
pub mode: RequestMode,
pub cache_mode: CacheMode,
pub use_cors_preflight: bool,
pub credentials_mode: CredentialsMode,
pub use_url_credentials: bool,
// this should actually be set by fetch, but fetch
// doesn't have info about the client right now
pub origin: ServoUrl,
// XXXManishearth these should be part of the client object
pub referrer_url: Option<ServoUrl>,
pub referrer_policy: Option<ReferrerPolicy>,
pub pipeline_id: Option<PipelineId>,
pub redirect_mode: RedirectMode,
pub integrity_metadata: String,
// to keep track of redirects
pub url_list: Vec<ServoUrl>,
}
impl Default for RequestInit {
fn default() -> RequestInit {
RequestInit {
method: Method::Get,
url: ServoUrl::parse("about:blank").unwrap(),
headers: Headers::new(),
unsafe_request: false,
body: None,
service_workers_mode: ServiceWorkersMode::All,
type_: Type::None,
destination: Destination::None,
synchronous: false,
mode: RequestMode::NoCors,
cache_mode: CacheMode::Default,
use_cors_preflight: false,
credentials_mode: CredentialsMode::Omit,
use_url_credentials: false,
origin: ServoUrl::parse("about:blank").unwrap(),
referrer_url: None,
referrer_policy: None,
pipeline_id: None,
redirect_mode: RedirectMode::Follow,
integrity_metadata: "".to_owned(),
url_list: vec![],
}
}
}
/// A [Request](https://fetch.spec.whatwg.org/#concept-request) as defined by
/// the Fetch spec.
#[derive(Clone, HeapSizeOf)]
pub struct Request {
/// https://fetch.spec.whatwg.org/#concept-request-method
#[ignore_heap_size_of = "Defined in hyper"]
pub method: Method,
/// https://fetch.spec.whatwg.org/#local-urls-only-flag
pub local_urls_only: bool,
/// https://fetch.spec.whatwg.org/#sandboxed-storage-area-urls-flag
pub sandboxed_storage_area_urls: bool,
/// https://fetch.spec.whatwg.org/#concept-request-header-list
#[ignore_heap_size_of = "Defined in hyper"]
pub headers: Headers,
/// https://fetch.spec.whatwg.org/#unsafe-request-flag
pub unsafe_request: bool,
/// https://fetch.spec.whatwg.org/#concept-request-body
pub body: Option<Vec<u8>>,
// TODO: client object
pub window: Window,
// TODO: target browsing context
/// https://fetch.spec.whatwg.org/#request-keepalive-flag
pub keep_alive: bool,
// https://fetch.spec.whatwg.org/#request-service-workers-mode
pub service_workers_mode: ServiceWorkersMode,
/// https://fetch.spec.whatwg.org/#concept-request-initiator
pub initiator: Initiator,
/// https://fetch.spec.whatwg.org/#concept-request-type
pub type_: Type,
/// https://fetch.spec.whatwg.org/#concept-request-destination
pub destination: Destination,
// TODO: priority object
/// https://fetch.spec.whatwg.org/#concept-request-origin
pub origin: Origin,
/// https://fetch.spec.whatwg.org/#concept-request-referrer
pub referrer: Referrer,
/// https://fetch.spec.whatwg.org/#concept-request-referrer-policy
pub referrer_policy: Option<ReferrerPolicy>,
pub pipeline_id: Option<PipelineId>,
/// https://fetch.spec.whatwg.org/#synchronous-flag
pub synchronous: bool,
/// https://fetch.spec.whatwg.org/#concept-request-mode
pub mode: RequestMode,
/// https://fetch.spec.whatwg.org/#use-cors-preflight-flag
pub use_cors_preflight: bool,
/// https://fetch.spec.whatwg.org/#concept-request-credentials-mode
pub credentials_mode: CredentialsMode,
/// https://fetch.spec.whatwg.org/#concept-request-use-url-credentials-flag
pub use_url_credentials: bool,
/// https://fetch.spec.whatwg.org/#concept-request-cache-mode
pub cache_mode: CacheMode,
/// https://fetch.spec.whatwg.org/#concept-request-redirect-mode
pub redirect_mode: RedirectMode,
/// https://fetch.spec.whatwg.org/#concept-request-integrity-metadata
pub integrity_metadata: String,
// Use the last method on url_list to act as spec current url field, and
// first method to act as spec url field
/// https://fetch.spec.whatwg.org/#concept-request-url-list
pub url_list: Vec<ServoUrl>,
/// https://fetch.spec.whatwg.org/#concept-request-redirect-count
pub redirect_count: u32,
/// https://fetch.spec.whatwg.org/#concept-request-response-tainting
pub response_tainting: ResponseTainting,
}
impl Request {
pub fn new(url: ServoUrl,
origin: Option<Origin>,
pipeline_id: Option<PipelineId>)
-> Request {
Request {
method: Method::Get,
local_urls_only: false,
sandboxed_storage_area_urls: false,
headers: Headers::new(),
unsafe_request: false,
body: None,
window: Window::Client,
keep_alive: false,
service_workers_mode: ServiceWorkersMode::All,
initiator: Initiator::None,
type_: Type::None,
destination: Destination::None,
origin: origin.unwrap_or(Origin::Client),
referrer: Referrer::Client,
referrer_policy: None,
pipeline_id: pipeline_id,
synchronous: false,
mode: RequestMode::NoCors,
use_cors_preflight: false,
credentials_mode: CredentialsMode::Omit,
use_url_credentials: false,
cache_mode: CacheMode::Default,
redirect_mode: RedirectMode::Follow,
integrity_metadata: String::new(),
url_list: vec![url],
redirect_count: 0,
response_tainting: ResponseTainting::Basic,
}
}
pub fn from_init(init: RequestInit) -> Request {
let mut req = Request::new(init.url.clone(),
Some(Origin::Origin(init.origin.origin())),
init.pipeline_id);
req.method = init.method;
req.headers = init.headers;
req.unsafe_request = init.unsafe_request;
req.body = init.body;
req.service_workers_mode = init.service_workers_mode;
req.type_ = init.type_;
req.destination = init.destination;
req.synchronous = init.synchronous;
req.mode = init.mode;
req.use_cors_preflight = init.use_cors_preflight;
req.credentials_mode = init.credentials_mode;
req.use_url_credentials = init.use_url_credentials;
req.cache_mode = init.cache_mode;
req.referrer = if let Some(url) = init.referrer_url {
Referrer::ReferrerUrl(url)
} else {
Referrer::NoReferrer
};
req.referrer_policy = init.referrer_policy;
req.pipeline_id = init.pipeline_id;
req.redirect_mode = init.redirect_mode;
let mut url_list = init.url_list;
if url_list.is_empty() {
url_list.push(init.url);
}
req.redirect_count = url_list.len() as u32 - 1;
req.url_list = url_list;
req.integrity_metadata = init.integrity_metadata;
req
}
/// https://fetch.spec.whatwg.org/#concept-request-url
pub fn url(&self) -> ServoUrl {
self.url_list.first().unwrap().clone()
}
/// https://fetch.spec.whatwg.org/#concept-request-current-url
pub fn current_url(&self) -> ServoUrl {
self.url_list.last().unwrap().clone()
}
/// https://fetch.spec.whatwg.org/#concept-request-current-url
pub fn current_url_mut(&mut self) -> &mut ServoUrl {
self.url_list.last_mut().unwrap()
}
/// https://fetch.spec.whatwg.org/#navigation-request
pub fn is_navigation_request(&self) -> bool {
self.destination == Destination::Document
}
/// https://fetch.spec.whatwg.org/#subresource-request
pub fn is_subresource_request(&self) -> bool {
match self.destination {
Destination::Font | Destination::Image | Destination::Manifest | Destination::Media |
Destination::Script | Destination::Style | Destination::XSLT | Destination::None => true,
_ => false,
}
}
}
impl Referrer {
pub fn to_url(&self) -> Option<&ServoUrl> {
match *self {
Referrer::NoReferrer | Referrer::Client => None,
Referrer::ReferrerUrl(ref url) => Some(url),
}
}
}<|fim▁end|> | /// A request [destination](https://fetch.spec.whatwg.org/#concept-request-destination) |
<|file_name|>get_locals.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import rospy
import actionlib
from actionlib_msgs.msg import *
from geometry_msgs.msg import PoseStampted
import yaml
import os
import os.path
class GetLocals:
def __init__(self):
rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback)
print('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n')
def goal_callback(self, data):
self.fname = os.path.expanduser('~') + '/catkin_ws/src/approach_control/approach_control_config/config/locals.yaml'
stream = open(self.fname, 'r')
self.data = yaml.load(stream)
self.keys = self.data.keys()
local = raw_input('Please, write the location for this point (if doesnt exist it will be create): \n options: ' + str(self.keys))
if [x for x in self.keys if x == local]:
self.data[local] = [[data.pose.position.x, data.pose.position.y], [0.0, 0.0, data.pose.orientation.z, data.pose.orientation.w]]
with open(self.fname, 'w') as yaml_file:<|fim▁hole|> c = raw_input('Save as a new place? (Y/N)')
if c.lower() == 'y':
self.data[local] = [[data.pose.position.x, data.pose.position.y], [0.0, 0.0, data.pose.orientation.z, data.pose.orientation.w]]
with open(self.fname, 'w') as yaml_file:
yaml_file.write(yaml.dump(self.data, default_flow_style = False))
rospy.loginfo('Point Saved!')
rospy.loginfo('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n')
else:
rospy.logerr('Point not Saved!')
rospy.loginfo('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n')
if __name__ == '__main__':
GetLocals()
rospy.init_node('getlocals', anonymous = True)
try:
rospy.spin()
except KeyboardInterrupt:
rospy.loginfo('Shutting down!')<|fim▁end|> | yaml_file.write(yaml.dump(self.data, default_flow_style = False))
rospy.loginfo('Point Saved!')
rospy.loginfo('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC USER INTERFACE TO SAVE A POINT!\n')
else: |
<|file_name|>codeUtility.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: latin-1 -*-
# Copyright 2015 Oeyvind Brandtsegg
#
# This file is part of the Signal Interaction Toolkit
#
# The Signal Interaction Toolkit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# The Signal Interaction Toolkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with The Signal Interaction Toolkit.
# If not, see <http://www.gnu.org/licenses/>.
import sys
if sys.argv[1] == 'template':
effectname = 'template'
parameters = [('Vol', (0.0, 1.0, 0.5, 0.25, 0.00001))]
# pName, (min, max, default, skew, increment)
# where skew is a dynamic adjustment of exp/lin/log translation if the GUI widget
# and increment is the smallest change allowed by the GUI widget
if sys.argv[1] == 'stereopan':
effectname = 'stereopan'
parameters = [('Pan', (0.0, 1.0, 0.5, 1, 0.001)),
('Mix', (0.0, 1.0, 0.5, 1, 0.001))]
if sys.argv[1] == 'tremolam':
effectname = 'tremolam'
parameters = [('Depth', (0.0, 1.0, 0.5, 0.25, 0.001)),
('RateLow', (0.0, 10.0, 0.5, 0.25, 0.001)),
('RateHigh', (0.0, 500.0, 0.5, 0.25, 0.001))]
if sys.argv[1] == 'vst_mediator':
effectname = 'vst_mediator'
parameters = [('parm1', (0.0, 1.0, 0.5, 1, 0.001)),
('parm2', (0.0, 1.0, 0.5, 1, 0.001)),
('parm3', (0.0, 1.0, 0.5, 1, 0.001)),
('parm4', (0.0, 1.0, 0.5, 1, 0.001)),
('parm5', (0.0, 1.0, 0.5, 1, 0.001)),
('parm6', (0.0, 1.0, 0.5, 1, 0.001)),
('parm7', (0.0, 1.0, 0.5, 1, 0.001)),
('parm8', (0.0, 1.0, 0.5, 1, 0.001))
]
if sys.argv[1] == 'vst_MIDIator':
effectname = 'vst_MIDIator'
parameters = [('parm1', (0.0, 1.0, 0.5, 1, 0.001)),
('parm2', (0.0, 1.0, 0.5, 1, 0.001)),
('parm3', (0.0, 1.0, 0.5, 1, 0.001)),
('parm4', (0.0, 1.0, 0.5, 1, 0.001)),
('parm5', (0.0, 1.0, 0.5, 1, 0.001)),
('parm6', (0.0, 1.0, 0.5, 1, 0.001)),
('parm7', (0.0, 1.0, 0.5, 1, 0.001)),
('parm8', (0.0, 1.0, 0.5, 1, 0.001))
]
if sys.argv[1] == 'stereodelay':
effectname = 'stereodelay'
parameters = [('delaytime', (0.0008, 2.0, 0.5, 0.25, 0.00001)),
('filt_fq', (100, 10000, 1000, 0.35, 1)),
('feedback', (0.0, 0.9999, 0.3, 1.9, 0.0001))
]
if sys.argv[1] == 'pluck':
effectname = 'pluck'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('freq', (1, 1450, 400, 0.3, 0.01)),
('filt_fq', (1000, 16000, 7000, 0.35, 1)),
('feedback', (0.8, 0.9999, 0.95, 1.9, 0.0001)),
('mix', (0, 1.0, 1, 0.3, 0.01))
]
if sys.argv[1] == 'lpf18dist':
effectname = 'lpf18dist'
parameters = [('Drive', (1, 12, 2, 1, 0.1)),
('Freq', (20, 10000, 3000, 0.35, 1)),
('Resonance', (0.001, 0.95, 0.3, 1, 0.001)),
('Dist', (0.001, 10, 0.2, 0.5, 0.001)),
('Mix', (0.0, 1.0, 1.0, 1, 0.01)),
]
if sys.argv[1] == 'screverb':
effectname = 'screverb'
parameters = [('InLevel', (0, 1.0, 0.2, 0.3, 0.01)),
('Feed', (0.0, 1.0, 0.85, 1.2, 0.01)),
('FiltFq', (100, 14000, 7000, 0.6, 1)),
('PitchMod', (0.0, 4.0, 0.9, 1, 0.01)),
('PreDly', (0.0, 500, 120, 1, 1)), <|fim▁hole|>
if sys.argv[1] == 'freeverb':
effectname = 'freeverb'
parameters = [('inlevel', (0, 1.0, 1.0, 0.3, 0.01)),
('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)),
('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)),
('reverbmix', (0.0, 1.0, 0.7, 1, 0.01))
]
if sys.argv[1] == 'mincertime':
effectname = 'mincertime'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('timpoint', (0, 0.99, 0.1, 0.4, 0.001)),
('pitch', (0.0, 2.0, 1.0, 1, 0.01)),
('feedback', (0.0, 1.0, 0.0, 1, 0.01)),
('mix', (0, 1.0, 1, 0.3, 0.01))
]
if sys.argv[1] == 'plucktremlpfverb':
effectname = 'plucktremlpfverb'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('pluckfreq', (1, 1450, 400, 0.3, 0.01)),
('pluckfilt', (1000, 16000, 7000, 0.35, 1)),
('pluckfeed', (0.8, 0.9999, 0.95, 1.9, 0.0001)),
('pluckmix', (0, 1.0, 1, 0.3, 0.01)),
('tremDepth', (0.0, 1.0, 0.5, 0.25, 0.001)),
('tRateLow', (0.0, 10.0, 0.5, 0.25, 0.001)),
('tRateHigh', (0.0, 500.0, 0.5, 0.25, 0.001)),
('lpfDrive', (1, 12, 2, 1, 0.1)),
('lpfFreq', (20, 10000, 3000, 0.35, 1)),
('lpfResonance', (0.001, 0.95, 0.3, 1, 0.001)),
('lpfDist', (0.001, 10, 0.2, 0.5, 0.001)),
('lpfMix', (0.0, 1.0, 1.0, 1, 0.01)),
('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)),
('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)),
('reverbmix', (0.0, 1.0, 0.7, 1, 0.01))
]
if sys.argv[1] == 'mincerpanverb':
effectname = 'mincerpanverb'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('mincertime', (0, 0.99, 0.1, 0.4, 0.001)),
('mincerpitch', (0.0, 2.0, 1.0, 1, 0.01)),
('mincerfeed', (0.0, 1.0, 0.0, 1, 0.01)),
('mincermix', (0, 1.0, 1, 0.3, 0.01)),
('Pan', (0.0, 1.0, 0.5, 1, 0.001)),
('panMix', (0.0, 1.0, 0.5, 1, 0.001)),
('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)),
('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)),
('reverbmix', (0.0, 1.0, 0.7, 1, 0.01))
]
#
scorefile = open(effectname+'_score_events.inc', 'w')
fractionalinstr = 0
for p in parameters:
fractionalinstr += 1
scorefile.write('i4.{fracinstr:02d} 3.1 $SCORELEN "{pname}"\n'.format(fracinstr=fractionalinstr, pname=p[0]))
#
chn_init_file = open(effectname+'_parameter_ranges.inc', 'w')
instr_template = '''
instr 1
; list of min and max for the mappable parameters
{}
endin
'''
parameter_ranges = ''
for i in range(len(parameters)):
parm = parameters[i]
parameter_ranges += ' chnset {}, "{}_min" \n'.format(parm[1][0], parm[0])
parameter_ranges += ' chnset {}, "{}_max" \n'.format(parm[1][1], parm[0])
chn_init_file.write(instr_template.format(parameter_ranges))
#
start_x_pos = 30
start_y_pos = 5
plant_height = 85
analysis_parms = '"rms", "rms_preEq", "cps", "pitch", "centroid", "spread", "skewness", "kurtosis", "flatness", "crest", "flux", "amp_trans", "amp_t_dens", "centr_trans", "centr_t_dens", "kurt_trans", "pitchup_trans", "pitchdown_trans", "cps_raw"'
plant = '''groupbox bounds({start_y}, {start_x}, 564, 81), plant("plant_{pname}"), linethickness("0"){{
combobox channel("source1_{pname}"), bounds(10, 12, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan1_{pname}"), bounds(103, 12, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 14, 35, 15), channel("rise1_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 14, 35, 15), channel("fall1_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 12, 86, 20), channel("scale1_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 12, 29, 19), channel("scale1_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 12, 86, 20), channel("curve1_{pname}"), range(-5.0, 5.0, 0)
combobox channel("source2_{pname}"), bounds(10, 34, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan2_{pname}"), bounds(103, 34, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 36, 35, 15), channel("rise2_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 36, 35, 15), channel("fall2_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 34, 86, 20), channel("scale2_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 34, 29, 19), channel("scale2_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 34, 86, 20), channel("curve2_{pname}"), range(-5.0, 5.0, 0)
label bounds(10, 58, 90, 12), text("source"), colour(20,20,20,255)
label bounds(103, 58, 50, 12), text("chan"), colour(20,20,20,255)
label bounds(156, 58, 76, 12), text("rise/fall"), colour(20,20,20,255)
label bounds(236, 58, 110, 12), text("scale"), colour(20,20,20,255)
label bounds(352, 58, 81, 12), text("curve"), colour(20,20,20,255)
rslider bounds(433, 12, 62, 62), text("offset"), channel("offset_{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
combobox bounds(433, 1, 55, 12), channel("offsetx_{pname}"), items("-1", "Nornm", "+1"), , value(2), channeltype("string")
rslider bounds(494, 8, 66, 66), text("{pname}"), channel("{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
}}
'''
plantMIDI = '''groupbox bounds({start_y}, {start_x}, 710, 81), plant("plant_{pname}"), linethickness("0"){{
combobox channel("source1_{pname}"), bounds(10, 12, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan1_{pname}"), bounds(103, 12, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 14, 35, 15), channel("rise1_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 14, 35, 15), channel("fall1_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 12, 86, 20), channel("scale1_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 12, 29, 19), channel("scale1_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 12, 86, 20), channel("curve1_{pname}"), range(-5.0, 5.0, 0)
combobox channel("source2_{pname}"), bounds(10, 34, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan2_{pname}"), bounds(103, 34, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 36, 35, 15), channel("rise2_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 36, 35, 15), channel("fall2_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 34, 86, 20), channel("scale2_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 34, 29, 19), channel("scale2_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 34, 86, 20), channel("curve2_{pname}"), range(-5.0, 5.0, 0)
label bounds(10, 58, 90, 12), text("source"), colour(20,20,20,255)
label bounds(103, 58, 50, 12), text("chan"), colour(20,20,20,255)
label bounds(156, 58, 76, 12), text("rise/fall"), colour(20,20,20,255)
label bounds(236, 58, 110, 12), text("scale"), colour(20,20,20,255)
label bounds(352, 58, 81, 12), text("curve"), colour(20,20,20,255)
rslider bounds(433, 12, 62, 62), text("offset"), channel("offset_{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
combobox bounds(433, 1, 55, 12), channel("offsetx_{pname}"), items("-1", "Nornm", "+1"), , value(2), channeltype("string")
rslider bounds(494, 8, 66, 66), text("{pname}"), channel("{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
label bounds(570, 8, 55, 12), text("midi"), colour(20,20,20,255)
checkbox bounds(632, 8, 12, 12), text("enable"), channel("enable_{pname}"), value(1)
numberbox bounds(570, 25, 55, 15), channel("midich_{pname}"), range(1, 16, 1)
numberbox bounds(570, 42, 55, 15), channel("ctrlnum_{pname}"), range(1, 127, 1)
label bounds(632, 25, 70, 12), text("channel"), colour(20,20,20,255)
label bounds(632, 42, 70, 12), text("ctrl"), colour(20,20,20,255)
}}
'''
if effectname == 'vst_MIDIator': plant = plantMIDI
guifile = open(effectname+'_gui_scratchpad.inc', 'w')
x_pos = start_x_pos
x_pos1 = start_x_pos
y_pos = start_y_pos
for i in range(len(parameters)):
parm = parameters[i]
if (effectname == 'plucktremlpfverb') and (parm[0] == 'lpfDrive'):
x_pos1 = x_pos
x_pos = start_x_pos
y_pos = 575
guifile.write(plant.format(start_x=x_pos, start_y=y_pos, pname=parm[0], analysis_p=analysis_parms,p_min=parm[1][0], p_max=parm[1][1], p_default=parm[1][2], p_skew=parm[1][3], p_incr=parm[1][4]))
x_pos+=plant_height
guifile.write(';next x position available below plants is {}'.format(max([x_pos,x_pos1])))<|fim▁end|> | ('LfRoll', (20, 500, 90, 1, 1)),
('Mix', (0.0, 1.0, 1.0, 1, 0.01))
] |
<|file_name|>binlog_purge_ms.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
binlog_purge_rpl test for ms test and BUG#22543517 running binlogpurge
on second master added to slave replication channels
"""
import replicate_ms
from mysql.utilities.exception import MUTLibError
_CHANGE_MASTER = ("CHANGE MASTER TO MASTER_HOST = 'localhost', "
"MASTER_USER = 'rpl', MASTER_PASSWORD = 'rpl', "
"MASTER_PORT = {0}, MASTER_AUTO_POSITION=1 "
"FOR CHANNEL 'master-{1}'")
def flush_server_logs_(server, times=5):
"""Flush logs on a server
server[in] the instance server where to flush logs on
times[in] number of times to flush the logs.
"""
# Flush master binary log
server.exec_query("SET sql_log_bin = 0")
for _ in range(times):
server.exec_query("FLUSH LOCAL BINARY LOGS")
server.exec_query("SET sql_log_bin = 1")
class test(replicate_ms.test):
"""test binlog purge Utility
This test runs the mysqlbinlogpurge utility on a known topology.
"""
master_datadir = None
slaves = None
mask_ports = []
def check_prerequisites(self):
if not self.servers.get_server(0).check_version_compat(5, 7, 6):
raise MUTLibError("Test requires server version 5.7.6 or later")
return self.check_num_servers(1)
def setup(self):
self.res_fname = "result.txt"
res = super(test, self).setup()
if not res:
return False
# Setup multiple channels for slave
m1_dict = self.get_connection_values(self.server2)
m2_dict = self.get_connection_values(self.server3)
for master in [self.server2, self.server3]:
master.exec_query("SET SQL_LOG_BIN= 0")
master.exec_query("GRANT REPLICATION SLAVE ON *.* TO 'rpl'@'{0}' "
"IDENTIFIED BY 'rpl'".format(self.server1.host))
master.exec_query("SET SQL_LOG_BIN= 1")
self.server1.exec_query("SET GLOBAL relay_log_info_repository = "
"'TABLE'")
self.server1.exec_query(_CHANGE_MASTER.format(m1_dict[3], 1))
self.server1.exec_query(_CHANGE_MASTER.format(m2_dict[3], 2))
self.server1.exec_query("START SLAVE")
return True
def run(self):
test_num = 0
master1_conn = self.build_connection_string(self.server2).strip(' ')
master2_conn = self.build_connection_string(self.server3).strip(' ')
cmd_str = "mysqlbinlogpurge.py --master={0} ".format(master1_conn)
cmd_opts = ("--discover-slaves={0} --dry-run "
"".format(master1_conn.split('@')[0]))
test_num += 1
comment = ("Test case {0} - mysqlbinlogpurge: with discover "
"and verbose options - master 1".format(test_num))
cmds = ("{0} {1} {2} -vv"
"").format(cmd_str, cmd_opts, "binlog_purge{0}.log".format(1))
res = self.run_test_case(0, cmds, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
flush_server_logs_(self.server1)
cmd_str = "mysqlbinlogpurge.py --master={0} ".format(master2_conn)
test_num += 1
comment = ("Test case {0} - mysqlbinlogpurge: with discover "
"and verbose options - master 2".format(test_num))
cmds = ("{0} {1} {2} -vv"<|fim▁hole|> if not res:
raise MUTLibError("{0}: failed".format(comment))
flush_server_logs_(self.server1)
super(test, self).reset_ms_topology()
return True
def get_result(self):
# If run method executes successfully without throwing any exceptions,
# then test was successful
return True, None
def record(self):
# Not a comparative test
return True
def cleanup(self):
return super(test, self).cleanup()<|fim▁end|> | "").format(cmd_str, cmd_opts, "binlog_purge{0}.log".format(2))
res = self.run_test_case(0, cmds, comment) |
<|file_name|>mklivestatus.py<|end_file_name|><|fim▁begin|><|fim▁hole|>PORT = 6557<|fim▁end|> | # Configs for mk-livestatus lookup scripts
HOST = [ 'nagios', 'nagios1' ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.