text
stringlengths 2
1.04M
| meta
dict |
---|---|
package org.apache.accumulo.core.client.mapreduce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.user.RegExFilter;
import org.apache.accumulo.core.iterators.user.WholeRowIterator;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.util.Base64;
import org.apache.accumulo.core.util.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Test;
public class AccumuloInputFormatTest {
private static final String PREFIX = AccumuloInputFormatTest.class.getSimpleName();
/**
* Check that the iterator configuration is getting stored in the Job conf correctly.
*/
@Test
public void testSetIterator() throws IOException {
Job job = Job.getInstance();
IteratorSetting is = new IteratorSetting(1, "WholeRow", "org.apache.accumulo.core.iterators.WholeRowIterator");
AccumuloInputFormat.addIterator(job, is);
Configuration conf = job.getConfiguration();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
is.write(new DataOutputStream(baos));
String iterators = conf.get("AccumuloInputFormat.ScanOpts.Iterators");
assertEquals(Base64.encodeBase64String(baos.toByteArray()), iterators);
}
@Test
public void testAddIterator() throws IOException {
Job job = Job.getInstance();
AccumuloInputFormat.addIterator(job, new IteratorSetting(1, "WholeRow", WholeRowIterator.class));
AccumuloInputFormat.addIterator(job, new IteratorSetting(2, "Versions", "org.apache.accumulo.core.iterators.VersioningIterator"));
IteratorSetting iter = new IteratorSetting(3, "Count", "org.apache.accumulo.core.iterators.CountingIterator");
iter.addOption("v1", "1");
iter.addOption("junk", "\0omg:!\\xyzzy");
AccumuloInputFormat.addIterator(job, iter);
List<IteratorSetting> list = AccumuloInputFormat.getIterators(job);
// Check the list size
assertTrue(list.size() == 3);
// Walk the list and make sure our settings are correct
IteratorSetting setting = list.get(0);
assertEquals(1, setting.getPriority());
assertEquals("org.apache.accumulo.core.iterators.user.WholeRowIterator", setting.getIteratorClass());
assertEquals("WholeRow", setting.getName());
assertEquals(0, setting.getOptions().size());
setting = list.get(1);
assertEquals(2, setting.getPriority());
assertEquals("org.apache.accumulo.core.iterators.VersioningIterator", setting.getIteratorClass());
assertEquals("Versions", setting.getName());
assertEquals(0, setting.getOptions().size());
setting = list.get(2);
assertEquals(3, setting.getPriority());
assertEquals("org.apache.accumulo.core.iterators.CountingIterator", setting.getIteratorClass());
assertEquals("Count", setting.getName());
assertEquals(2, setting.getOptions().size());
assertEquals("1", setting.getOptions().get("v1"));
assertEquals("\0omg:!\\xyzzy", setting.getOptions().get("junk"));
}
/**
* Test adding iterator options where the keys and values contain both the FIELD_SEPARATOR character (':') and ITERATOR_SEPARATOR (',') characters. There
* should be no exceptions thrown when trying to parse these types of option entries.
*
* This test makes sure that the expected raw values, as appears in the Job, are equal to what's expected.
*/
@Test
public void testIteratorOptionEncoding() throws Throwable {
String key = "colon:delimited:key";
String value = "comma,delimited,value";
IteratorSetting someSetting = new IteratorSetting(1, "iterator", "Iterator.class");
someSetting.addOption(key, value);
Job job = Job.getInstance();
AccumuloInputFormat.addIterator(job, someSetting);
List<IteratorSetting> list = AccumuloInputFormat.getIterators(job);
assertEquals(1, list.size());
assertEquals(1, list.get(0).getOptions().size());
assertEquals(list.get(0).getOptions().get(key), value);
someSetting.addOption(key + "2", value);
someSetting.setPriority(2);
someSetting.setName("it2");
AccumuloInputFormat.addIterator(job, someSetting);
list = AccumuloInputFormat.getIterators(job);
assertEquals(2, list.size());
assertEquals(1, list.get(0).getOptions().size());
assertEquals(list.get(0).getOptions().get(key), value);
assertEquals(2, list.get(1).getOptions().size());
assertEquals(list.get(1).getOptions().get(key), value);
assertEquals(list.get(1).getOptions().get(key + "2"), value);
}
/**
* Test getting iterator settings for multiple iterators set
*/
@Test
public void testGetIteratorSettings() throws IOException {
Job job = Job.getInstance();
AccumuloInputFormat.addIterator(job, new IteratorSetting(1, "WholeRow", "org.apache.accumulo.core.iterators.WholeRowIterator"));
AccumuloInputFormat.addIterator(job, new IteratorSetting(2, "Versions", "org.apache.accumulo.core.iterators.VersioningIterator"));
AccumuloInputFormat.addIterator(job, new IteratorSetting(3, "Count", "org.apache.accumulo.core.iterators.CountingIterator"));
List<IteratorSetting> list = AccumuloInputFormat.getIterators(job);
// Check the list size
assertTrue(list.size() == 3);
// Walk the list and make sure our settings are correct
IteratorSetting setting = list.get(0);
assertEquals(1, setting.getPriority());
assertEquals("org.apache.accumulo.core.iterators.WholeRowIterator", setting.getIteratorClass());
assertEquals("WholeRow", setting.getName());
setting = list.get(1);
assertEquals(2, setting.getPriority());
assertEquals("org.apache.accumulo.core.iterators.VersioningIterator", setting.getIteratorClass());
assertEquals("Versions", setting.getName());
setting = list.get(2);
assertEquals(3, setting.getPriority());
assertEquals("org.apache.accumulo.core.iterators.CountingIterator", setting.getIteratorClass());
assertEquals("Count", setting.getName());
}
@Test
public void testSetRegex() throws IOException {
Job job = Job.getInstance();
String regex = ">\"*%<>\'\\";
IteratorSetting is = new IteratorSetting(50, regex, RegExFilter.class);
RegExFilter.setRegexs(is, regex, null, null, null, false);
AccumuloInputFormat.addIterator(job, is);
assertTrue(regex.equals(AccumuloInputFormat.getIterators(job).get(0).getName()));
}
private static AssertionError e1 = null;
private static AssertionError e2 = null;
private static class MRTester extends Configured implements Tool {
private static class TestMapper extends Mapper<Key,Value,Key,Value> {
Key key = null;
int count = 0;
@Override
protected void map(Key k, Value v, Context context) throws IOException, InterruptedException {
try {
if (key != null)
assertEquals(key.getRow().toString(), new String(v.get()));
assertEquals(k.getRow(), new Text(String.format("%09x", count + 1)));
assertEquals(new String(v.get()), String.format("%09x", count));
} catch (AssertionError e) {
e1 = e;
}
key = new Key(k);
count++;
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
try {
assertEquals(100, count);
} catch (AssertionError e) {
e2 = e;
}
}
}
@Override
public int run(String[] args) throws Exception {
if (args.length != 5 && args.length != 6) {
throw new IllegalArgumentException("Usage : " + MRTester.class.getName() + " <user> <pass> <table> <instanceName> <inputFormatClass> [<batchScan>]");
}
String user = args[0];
String pass = args[1];
String table = args[2];
String instanceName = args[3];
String inputFormatClassName = args[4];
Boolean batchScan = false;
if (args.length == 6)
batchScan = Boolean.parseBoolean(args[5]);
@SuppressWarnings("unchecked")
Class<? extends InputFormat<?,?>> inputFormatClass = (Class<? extends InputFormat<?,?>>) Class.forName(inputFormatClassName);
Job job = Job.getInstance(getConf(), this.getClass().getSimpleName() + "_" + System.currentTimeMillis());
job.setJarByClass(this.getClass());
job.setInputFormatClass(inputFormatClass);
AccumuloInputFormat.setConnectorInfo(job, user, new PasswordToken(pass));
AccumuloInputFormat.setInputTableName(job, table);
AccumuloInputFormat.setMockInstance(job, instanceName);
AccumuloInputFormat.setBatchScan(job, batchScan);
job.setMapperClass(TestMapper.class);
job.setMapOutputKeyClass(Key.class);
job.setMapOutputValueClass(Value.class);
job.setOutputFormatClass(NullOutputFormat.class);
job.setNumReduceTasks(0);
job.waitForCompletion(true);
return job.isSuccessful() ? 0 : 1;
}
public static int main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("mapreduce.cluster.local.dir", new File(System.getProperty("user.dir"), "target/mapreduce-tmp").getAbsolutePath());
return ToolRunner.run(conf, new MRTester(), args);
}
}
@Test
public void testMap() throws Exception {
final String INSTANCE_NAME = PREFIX + "_mapreduce_instance";
final String TEST_TABLE_1 = PREFIX + "_mapreduce_table_1";
MockInstance mockInstance = new MockInstance(INSTANCE_NAME);
Connector c = mockInstance.getConnector("root", new PasswordToken(""));
c.tableOperations().create(TEST_TABLE_1);
BatchWriter bw = c.createBatchWriter(TEST_TABLE_1, new BatchWriterConfig());
for (int i = 0; i < 100; i++) {
Mutation m = new Mutation(new Text(String.format("%09x", i + 1)));
m.put(new Text(), new Text(), new Value(String.format("%09x", i).getBytes()));
bw.addMutation(m);
}
bw.close();
Assert.assertEquals(0, MRTester.main(new String[] {"root", "", TEST_TABLE_1, INSTANCE_NAME, AccumuloInputFormat.class.getName()}));
assertNull(e1);
assertNull(e2);
}
@Test
public void testMapWithBatchScanner() throws Exception {
final String INSTANCE_NAME = PREFIX + "_mapreduce_instance";
final String TEST_TABLE_2 = PREFIX + "_mapreduce_table_2";
MockInstance mockInstance = new MockInstance(INSTANCE_NAME);
Connector c = mockInstance.getConnector("root", new PasswordToken(""));
c.tableOperations().create(TEST_TABLE_2);
BatchWriter bw = c.createBatchWriter(TEST_TABLE_2, new BatchWriterConfig());
for (int i = 0; i < 100; i++) {
Mutation m = new Mutation(new Text(String.format("%09x", i + 1)));
m.put(new Text(), new Text(), new Value(String.format("%09x", i).getBytes()));
bw.addMutation(m);
}
bw.close();
Assert.assertEquals(0, MRTester.main(new String[] {"root", "", TEST_TABLE_2, INSTANCE_NAME, AccumuloInputFormat.class.getName(), "True"}));
assertNull(e1);
assertNull(e2);
}
@Test
public void testCorrectRangeInputSplits() throws Exception {
Job job = Job.getInstance(new Configuration(), this.getClass().getSimpleName() + "_" + System.currentTimeMillis());
String username = "user", table = "table", instance = "mapreduce_testCorrectRangeInputSplits";
PasswordToken password = new PasswordToken("password");
Authorizations auths = new Authorizations("foo");
Collection<Pair<Text,Text>> fetchColumns = Collections.singleton(new Pair<>(new Text("foo"), new Text("bar")));
boolean isolated = true, localIters = true;
Level level = Level.WARN;
Instance inst = new MockInstance(instance);
Connector connector = inst.getConnector(username, password);
connector.tableOperations().create(table);
AccumuloInputFormat.setConnectorInfo(job, username, password);
AccumuloInputFormat.setInputTableName(job, table);
AccumuloInputFormat.setScanAuthorizations(job, auths);
AccumuloInputFormat.setMockInstance(job, instance);
AccumuloInputFormat.setScanIsolation(job, isolated);
AccumuloInputFormat.setLocalIterators(job, localIters);
AccumuloInputFormat.fetchColumns(job, fetchColumns);
AccumuloInputFormat.setLogLevel(job, level);
AccumuloInputFormat aif = new AccumuloInputFormat();
List<InputSplit> splits = aif.getSplits(job);
Assert.assertEquals(1, splits.size());
InputSplit split = splits.get(0);
Assert.assertEquals(RangeInputSplit.class, split.getClass());
RangeInputSplit risplit = (RangeInputSplit) split;
Assert.assertEquals(username, risplit.getPrincipal());
Assert.assertEquals(table, risplit.getTableName());
Assert.assertEquals(password, risplit.getToken());
Assert.assertEquals(auths, risplit.getAuths());
Assert.assertEquals(instance, risplit.getInstanceName());
Assert.assertEquals(isolated, risplit.isIsolatedScan());
Assert.assertEquals(localIters, risplit.usesLocalIterators());
Assert.assertEquals(fetchColumns, risplit.getFetchedColumns());
Assert.assertEquals(level, risplit.getLogLevel());
}
@Test
public void testPartialInputSplitDelegationToConfiguration() throws Exception {
String user = "testPartialInputSplitUser";
PasswordToken password = new PasswordToken("");
MockInstance mockInstance = new MockInstance("testPartialInputSplitDelegationToConfiguration");
Connector c = mockInstance.getConnector(user, password);
c.tableOperations().create("testtable");
BatchWriter bw = c.createBatchWriter("testtable", new BatchWriterConfig());
for (int i = 0; i < 100; i++) {
Mutation m = new Mutation(new Text(String.format("%09x", i + 1)));
m.put(new Text(), new Text(), new Value(String.format("%09x", i).getBytes()));
bw.addMutation(m);
}
bw.close();
Assert.assertEquals(0,
MRTester.main(new String[] {user, "", "testtable", "testPartialInputSplitDelegationToConfiguration", EmptySplitsAccumuloInputFormat.class.getName()}));
assertNull(e1);
assertNull(e2);
}
@Test
public void testPartialFailedInputSplitDelegationToConfiguration() throws Exception {
String user = "testPartialFailedInputSplit";
PasswordToken password = new PasswordToken("");
MockInstance mockInstance = new MockInstance("testPartialFailedInputSplitDelegationToConfiguration");
Connector c = mockInstance.getConnector(user, password);
c.tableOperations().create("testtable");
BatchWriter bw = c.createBatchWriter("testtable", new BatchWriterConfig());
for (int i = 0; i < 100; i++) {
Mutation m = new Mutation(new Text(String.format("%09x", i + 1)));
m.put(new Text(), new Text(), new Value(String.format("%09x", i).getBytes()));
bw.addMutation(m);
}
bw.close();
// We should fail before we even get into the Mapper because we can't make the RecordReader
Assert.assertEquals(
1,
MRTester.main(new String[] {user, "", "testtable", "testPartialFailedInputSplitDelegationToConfiguration",
BadPasswordSplitsAccumuloInputFormat.class.getName()}));
assertNull(e1);
assertNull(e2);
}
@Test
public void testEmptyColumnFamily() throws IOException {
Job job = Job.getInstance();
Set<Pair<Text,Text>> cols = new HashSet<>();
cols.add(new Pair<Text,Text>(new Text(""), null));
cols.add(new Pair<>(new Text("foo"), new Text("bar")));
cols.add(new Pair<>(new Text(""), new Text("bar")));
cols.add(new Pair<>(new Text(""), new Text("")));
cols.add(new Pair<>(new Text("foo"), new Text("")));
AccumuloInputFormat.fetchColumns(job, cols);
Set<Pair<Text,Text>> setCols = AccumuloInputFormat.getFetchedColumns(job);
assertEquals(cols, setCols);
}
}
| {
"content_hash": "d844ae416c5dcda19abfb928e38737c6",
"timestamp": "",
"source": "github",
"line_count": 415,
"max_line_length": 159,
"avg_line_length": 40.86987951807229,
"alnum_prop": 0.7099817227757798,
"repo_name": "adamjshook/accumulo",
"id": "b39064f9ca8da7b7a3195ae67ffdef345475c32f",
"size": "17762",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/org/apache/accumulo/core/client/mapreduce/AccumuloInputFormatTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2423"
},
{
"name": "C++",
"bytes": "1414083"
},
{
"name": "CSS",
"bytes": "5933"
},
{
"name": "Groovy",
"bytes": "1385"
},
{
"name": "HTML",
"bytes": "11698"
},
{
"name": "Java",
"bytes": "20215877"
},
{
"name": "JavaScript",
"bytes": "249594"
},
{
"name": "Makefile",
"bytes": "2865"
},
{
"name": "Perl",
"bytes": "28190"
},
{
"name": "Protocol Buffer",
"bytes": "1325"
},
{
"name": "Python",
"bytes": "729147"
},
{
"name": "Ruby",
"bytes": "211593"
},
{
"name": "Shell",
"bytes": "194340"
},
{
"name": "Thrift",
"bytes": "55653"
}
],
"symlink_target": ""
} |
@interface PPAsyncImageView ()
@property (nonatomic, strong) NSString *loadingImageName;
@property (nonatomic, assign) BOOL isImageLoaded;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;
- (void) resetState;
@end
@implementation PPAsyncImageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.activityIndicatorView setCenter:[self center]];
[self.activityIndicatorView stopAnimating];
[self addSubview:self.activityIndicatorView];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self.activityIndicatorView setCenter:[self center]];
}
- (void)setImage:(UIImage *)image
{
[super setImage:image];
[self setIsImageLoaded:YES];
}
- (void)setImageName:(NSString *)imageName
{
[self setImageName:imageName loadImmediately:YES];
}
- (void)setImageName:(NSString *)imageName loadImmediately:(BOOL)loadImmediately
{
_imageName = imageName;
[self resetState];
if (loadImmediately) {
[self start];
}
}
- (void)start
{
if (self.isImageLoaded) {
return;
}
[self setIsImageLoaded:NO];
[self setLoadingImageName:self.imageName];
[self.activityIndicatorView startAnimating];
[[PPImageLoader sharedInstance] loadImageNamed:self.loadingImageName completion:^(NSString *imageName, UIImage *image){
if ([imageName isEqual:self.loadingImageName]) {
[self setIsImageLoaded:YES];
[self setLoadingImageName:nil];
[super setImage:image];
[self.activityIndicatorView stopAnimating];
}
}];
}
- (void)resetState
{
[self setIsImageLoaded:NO];
[self setLoadingImageName:nil];
[super setImage:nil];
[self.activityIndicatorView stopAnimating];
}
@end
| {
"content_hash": "dc95b7bbfaaf4f60c095a27e063b9c24",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 135,
"avg_line_length": 23.678571428571427,
"alnum_prop": 0.6892911010558069,
"repo_name": "peterwongpp/PPAsyncImageView",
"id": "3f1e27adc8a76a53038595cced36b9aedf495ea7",
"size": "2190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PPAsyncImageView/PPAsyncImageView.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "18709"
},
{
"name": "Ruby",
"bytes": "1355"
}
],
"symlink_target": ""
} |
package com.hazelcast.spi.properties;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IndeterminateOperationStateException;
import com.hazelcast.instance.BuildInfo;
import com.hazelcast.instance.BuildInfoProvider;
import com.hazelcast.internal.cluster.fd.ClusterFailureDetectorType;
import com.hazelcast.internal.diagnostics.HealthMonitorLevel;
import com.hazelcast.map.QueryResultSizeExceededException;
import com.hazelcast.map.impl.query.QueryResultSizeLimiter;
import com.hazelcast.query.TruePredicate;
import com.hazelcast.query.impl.IndexCopyBehavior;
import com.hazelcast.query.impl.predicates.QueryOptimizerFactory;
import com.hazelcast.spi.InvocationBuilder;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Defines the name and default value for Hazelcast properties.
*/
@SuppressWarnings("checkstyle:javadocvariable")
public final class GroupProperty {
/**
* Use this property to verify that Hazelcast nodes only join the cluster when their 'application' level configuration is the
* same.
* <p/>
* If you have multiple machines, you want to make sure that each machine that joins the cluster
* has exactly the same 'application level' settings (such as settings that are not part of the Hazelcast configuration,
* maybe some file path). To prevent the machines with potentially different application level configuration from forming
* a cluster, you can set this property.
* <p/>
* You could use actual values, such as string paths, but you can also use an md5 hash. We make a guarantee
* that nodes will form a cluster (become a member) only if the token is an exact match. If this token is different, the
* member can't be started and therefore you will get the guarantee that all members in the cluster will have exactly the same
* application validation token.
* <p/>
* This validation token will be checked before a member joins the cluster.
*/
public static final HazelcastProperty APPLICATION_VALIDATION_TOKEN
= new HazelcastProperty("hazelcast.application.validation.token");
/**
* Total number of partitions in the Hazelcast cluster.
*/
public static final HazelcastProperty PARTITION_COUNT
= new HazelcastProperty("hazelcast.partition.count", 271);
/**
* The number of partition operation handler threads per member.
* <p/>
* If this is less than the number of partitions on a member, partition operations
* will queue behind other operations of different partitions.
* <p/>
* The default is -1, which means that the value is determined dynamically.
*/
public static final HazelcastProperty PARTITION_OPERATION_THREAD_COUNT
= new HazelcastProperty("hazelcast.operation.thread.count", -1);
/**
* The number of generic operation handler threads per member.
* <p/>
* The default is -1, which means that the value is determined dynamically.
*/
public static final HazelcastProperty GENERIC_OPERATION_THREAD_COUNT
= new HazelcastProperty("hazelcast.operation.generic.thread.count", -1);
/**
* The number of priority generic operation handler threads per member.
* <p/>
* The default is 1.
* <p>
* Having at least 1 priority generic operation thread helps to improve cluster stability since a lot of cluster
* operations are generic priority operations and they should get executed as soon as possible. If there is a dedicated
* generic operation thread then these operations don't get delayed because the generic threads are busy executing regular
* user operations. So unless memory consumption is an issue, make sure there is at least 1 thread.
*/
public static final HazelcastProperty PRIORITY_GENERIC_OPERATION_THREAD_COUNT
= new HazelcastProperty("hazelcast.operation.priority.generic.thread.count", 1);
/**
* The number of threads that process responses.
* <p>
* By default there are 2 response threads; this gives stable and good performance.
* <p>
* If set to 0, the response threads are bypassed and the response handling is done
* on the IO threads. Under certain conditions this can give a higher throughput, but
* setting it to 0 should be regarded an experimental feature.
*/
public static final HazelcastProperty RESPONSE_THREAD_COUNT
= new HazelcastProperty("hazelcast.operation.response.thread.count", 2);
/**
* The number of threads that the client engine has available for processing requests that are not partition specific.
* Most of the requests, such as {@code map.put} and {@code map.get}, are partition specific and will use a
* partition-specific operation thread, but there are also requests that can't be executed on a partition-specific operation
* thread, such as {@code multimap.containsValue(value)}, because they need to access all partitions on a given
* member.
*/
public static final HazelcastProperty CLIENT_ENGINE_THREAD_COUNT
= new HazelcastProperty("hazelcast.clientengine.thread.count", -1);
public static final HazelcastProperty CLIENT_ENGINE_QUERY_THREAD_COUNT
= new HazelcastProperty("hazelcast.clientengine.query.thread.count", -1);
/**
* Time after which client connection is removed or owner node of a client is removed from the cluster.
* <p>
* ClientDisconnectionOperation runs and cleans all resources of a client (listeners are removed, locks/txn are released).
* With this property, client has a window to connect back and prevent cleaning up its resources.
*/
public static final HazelcastProperty CLIENT_ENDPOINT_REMOVE_DELAY_SECONDS
= new HazelcastProperty("hazelcast.client.endpoint.remove.delay.seconds", 60);
/**
* Number of threads for the {@link com.hazelcast.spi.impl.eventservice.impl.EventServiceImpl} executor.
* The executor is responsible for executing the events. If you process a lot of events and have many cores, setting
* a higher value is a good practice. This way, more events can be processed in parallel.
*/
public static final HazelcastProperty EVENT_THREAD_COUNT
= new HazelcastProperty("hazelcast.event.thread.count", 5);
/**
* The capacity of the {@link com.hazelcast.spi.impl.eventservice.impl.EventServiceImpl} executor.
* The executor is responsible for executing the events. If the events are produced at a higher rate than they are
* consumed, the queue grows in size. This can lead to an {@link OutOfMemoryError} if the accumulated events
* are not small enough to fit in memory. This capacity is shared between event topics.
* When the maximum capacity is reached, the items are dropped. This means that the event system is a 'best effort' system
* and there is no guarantee that you are going to get an event.
* Since the capacity is shared between topics, one topic might fill the entire queue and cause
* other topics to drop their messages.
*/
public static final HazelcastProperty EVENT_QUEUE_CAPACITY
= new HazelcastProperty("hazelcast.event.queue.capacity", 1000000);
/**
* The timeout for offering an event to the event executor for processing. If the event queue is full,
* the event might not be accepted to the queue and it will be dropped.
* This applies only to processing of local events. Remote events (events on a remote subscriber) have no timeout,
* meaning that the event can be rejected immediately.
*/
public static final HazelcastProperty EVENT_QUEUE_TIMEOUT_MILLIS
= new HazelcastProperty("hazelcast.event.queue.timeout.millis", 250, MILLISECONDS);
/**
* To prevent overloading of the outbound connections, once in a while an event is made synchronous by wrapping it in a
* fake operation and waiting for a fake response. This causes the outbound write queue of the connection to get drained.
* <p>
* This timeout configures the maximum amount of waiting time for this fake response. Setting it to a too low value
* can lead to an uncontrolled growth of the outbound write queue of the connection.
*/
public static final HazelcastProperty EVENT_SYNC_TIMEOUT_MILLIS
= new HazelcastProperty("hazelcast.event.sync.timeout.millis", 5000, MILLISECONDS);
public static final HazelcastProperty HEALTH_MONITORING_LEVEL
= new HazelcastProperty("hazelcast.health.monitoring.level", HealthMonitorLevel.SILENT.toString());
public static final HazelcastProperty HEALTH_MONITORING_DELAY_SECONDS
= new HazelcastProperty("hazelcast.health.monitoring.delay.seconds", 20, SECONDS);
public static final HazelcastProperty HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE
= new HazelcastProperty("hazelcast.health.monitoring.threshold.memory.percentage", 70);
public static final HazelcastProperty HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE
= new HazelcastProperty("hazelcast.health.monitoring.threshold.cpu.percentage", 70);
/**
* The number of threads doing socket input and the number of threads doing socket output.
* <p/>
* E.g., if 3 is configured, then you get 3 threads doing input and 3 doing output. For individual control,
* check {@link #IO_INPUT_THREAD_COUNT} and {@link #IO_OUTPUT_THREAD_COUNT}.
* <p/>
* The default is 3 (i.e. 6 threads).
*/
public static final HazelcastProperty IO_THREAD_COUNT
= new HazelcastProperty("hazelcast.io.thread.count", 3);
/**
* Controls the number of socket input threads. By default it is the same as {@link #IO_THREAD_COUNT}.
*/
public static final HazelcastProperty IO_INPUT_THREAD_COUNT
= new HazelcastProperty("hazelcast.io.input.thread.count", IO_THREAD_COUNT);
/**
* Controls the number of socket output threads. By default it is the same as {@link #IO_THREAD_COUNT}.
*/
public static final HazelcastProperty IO_OUTPUT_THREAD_COUNT
= new HazelcastProperty("hazelcast.io.output.thread.count", IO_THREAD_COUNT);
/**
* The interval in seconds between {@link com.hazelcast.internal.networking.nio.iobalancer.IOBalancer IOBalancer}
* executions. The shorter intervals will catch I/O Imbalance faster, but they will cause higher overhead.
* <p/>
* Please see the documentation of {@link com.hazelcast.internal.networking.nio.iobalancer.IOBalancer IOBalancer}
* for a detailed explanation of the problem.
* <p/>
* The default is 20 seconds. A value smaller than 1 disables the balancer.
*/
public static final HazelcastProperty IO_BALANCER_INTERVAL_SECONDS
= new HazelcastProperty("hazelcast.io.balancer.interval.seconds", 20, SECONDS);
@SuppressWarnings("checkstyle:constantname")
public static final HazelcastProperty PREFER_IPv4_STACK
= new HazelcastProperty("hazelcast.prefer.ipv4.stack", true);
@Deprecated
public static final HazelcastProperty VERSION_CHECK_ENABLED
= new HazelcastProperty("hazelcast.version.check.enabled", true);
public static final HazelcastProperty PHONE_HOME_ENABLED
= new HazelcastProperty("hazelcast.phone.home.enabled", true);
public static final HazelcastProperty CONNECT_ALL_WAIT_SECONDS
= new HazelcastProperty("hazelcast.connect.all.wait.seconds", 120, SECONDS);
public static final HazelcastProperty MEMCACHE_ENABLED
= new HazelcastProperty("hazelcast.memcache.enabled", false);
public static final HazelcastProperty REST_ENABLED
= new HazelcastProperty("hazelcast.rest.enabled", false);
public static final HazelcastProperty HTTP_HEALTHCHECK_ENABLED
= new HazelcastProperty("hazelcast.http.healthcheck.enabled", false);
/**
* The maximum size of the key batch sent to the partition owners for value loading
* and the maximum size of a key batch for which values are loaded in a single partition.
*/
public static final HazelcastProperty MAP_LOAD_CHUNK_SIZE
= new HazelcastProperty("hazelcast.map.load.chunk.size", 1000);
/**
* The delay until the first run of the {@link com.hazelcast.internal.cluster.impl.SplitBrainHandler}
*/
public static final HazelcastProperty MERGE_FIRST_RUN_DELAY_SECONDS
= new HazelcastProperty("hazelcast.merge.first.run.delay.seconds", 300, SECONDS);
/**
* The interval between invocations of the {@link com.hazelcast.internal.cluster.impl.SplitBrainHandler}
*/
public static final HazelcastProperty MERGE_NEXT_RUN_DELAY_SECONDS
= new HazelcastProperty("hazelcast.merge.next.run.delay.seconds", 120, SECONDS);
public static final HazelcastProperty OPERATION_CALL_TIMEOUT_MILLIS
= new HazelcastProperty("hazelcast.operation.call.timeout.millis", 60000, MILLISECONDS);
/**
* If an operation has backups, this property specifies how long the invocation will wait for acks from the backup replicas.
* If acks are not received from some backups, there will not be any rollback on other successful replicas.
*/
public static final HazelcastProperty OPERATION_BACKUP_TIMEOUT_MILLIS
= new HazelcastProperty("hazelcast.operation.backup.timeout.millis", 5000, MILLISECONDS);
/**
* When this configuration is enabled, if an operation has sync backups and acks are not received from backup replicas
* in time, or the member which owns primary replica of the target partition leaves the cluster, then the invocation fails
* with {@link IndeterminateOperationStateException}. However, even if the invocation fails,
* there will not be any rollback on other successful replicas.
*/
public static final HazelcastProperty FAIL_ON_INDETERMINATE_OPERATION_STATE
= new HazelcastProperty("hazelcast.operation.fail.on.indeterminate.state", false);
/**
* Maximum number of retries for an invocation. After threshold is reached, invocation is assumed as failed.
*/
public static final HazelcastProperty INVOCATION_MAX_RETRY_COUNT
= new HazelcastProperty("hazelcast.invocation.max.retry.count", InvocationBuilder.DEFAULT_TRY_COUNT);
/**
* Pause time between each retry cycle of an invocation in milliseconds.
*/
public static final HazelcastProperty INVOCATION_RETRY_PAUSE
= new HazelcastProperty("hazelcast.invocation.retry.pause.millis",
InvocationBuilder.DEFAULT_TRY_PAUSE_MILLIS, MILLISECONDS);
public static final HazelcastProperty SOCKET_BIND_ANY
= new HazelcastProperty("hazelcast.socket.bind.any", true);
public static final HazelcastProperty SOCKET_SERVER_BIND_ANY
= new HazelcastProperty("hazelcast.socket.server.bind.any", SOCKET_BIND_ANY);
public static final HazelcastProperty SOCKET_CLIENT_BIND_ANY
= new HazelcastProperty("hazelcast.socket.client.bind.any", SOCKET_BIND_ANY);
public static final HazelcastProperty SOCKET_CLIENT_BIND
= new HazelcastProperty("hazelcast.socket.client.bind", true);
// number of kilobytes
public static final HazelcastProperty SOCKET_RECEIVE_BUFFER_SIZE
= new HazelcastProperty("hazelcast.socket.receive.buffer.size", 128);
// number of kilobytes
public static final HazelcastProperty SOCKET_SEND_BUFFER_SIZE
= new HazelcastProperty("hazelcast.socket.send.buffer.size", 128);
/**
* If the bytebuffers used in the socket should be a direct bytebuffer (true) or a regular bytebuffer (false).
*/
public static final HazelcastProperty SOCKET_BUFFER_DIRECT
= new HazelcastProperty("hazelcast.socket.buffer.direct", false);
/**
* Overrides receive buffer size for connections opened by clients.
* <p/>
* Hazelcast creates all connections with receive buffer size set according to #PROP_SOCKET_RECEIVE_BUFFER_SIZE.
* When it detects a connection was opened by a client then it adjusts receive buffer size
* according to this property.
* <p/>
* Size is in kilobytes.
* <p/>
* The default is -1 (same as receive buffer size for connections opened by members).
*/
public static final HazelcastProperty SOCKET_CLIENT_RECEIVE_BUFFER_SIZE
= new HazelcastProperty("hazelcast.socket.client.receive.buffer.size", -1);
/**
* Overrides send buffer size for connections opened by clients.
* <p/>
* Hazelcast creates all connections with send buffer size set according to #PROP_SOCKET_SEND_BUFFER_SIZE.
* When it detects a connection was opened by a client then it adjusts send buffer size
* according to this property.
* <p/>
* Size is in kilobytes.
* <p/>
* The default is -1 (same as receive buffer size for connections opened by members).
*/
public static final HazelcastProperty SOCKET_CLIENT_SEND_BUFFER_SIZE
= new HazelcastProperty("hazelcast.socket.client.send.buffer.size", -1);
public static final HazelcastProperty SOCKET_CLIENT_BUFFER_DIRECT
= new HazelcastProperty("hazelcast.socket.client.buffer.direct", false);
public static final HazelcastProperty SOCKET_LINGER_SECONDS
= new HazelcastProperty("hazelcast.socket.linger.seconds", 0, SECONDS);
public static final HazelcastProperty SOCKET_CONNECT_TIMEOUT_SECONDS
= new HazelcastProperty("hazelcast.socket.connect.timeout.seconds", 0, SECONDS);
public static final HazelcastProperty SOCKET_KEEP_ALIVE
= new HazelcastProperty("hazelcast.socket.keep.alive", true);
public static final HazelcastProperty SOCKET_NO_DELAY
= new HazelcastProperty("hazelcast.socket.no.delay", true);
public static final HazelcastProperty SHUTDOWNHOOK_ENABLED
= new HazelcastProperty("hazelcast.shutdownhook.enabled", true);
/**
* Behaviour when JVM is about to exit while Hazelcast instance is still running.
*
* Possible values:
* TERMINATE: Terminate Hazelcast immediately
* GRACEFUL: Initiate graceful shutdown. This can significantly slow-down JVM exit process, but it's tries to
* retain data safety.
*
* Default: TERMINATE
*
* You should always shutdown Hazelcast explicitly via {@link HazelcastInstance#shutdown()}
* It's not recommended to rely on shutdown hook, this is a last-effort measure.
*/
public static final HazelcastProperty SHUTDOWNHOOK_POLICY
= new HazelcastProperty("hazelcast.shutdownhook.policy", "TERMINATE");
public static final HazelcastProperty WAIT_SECONDS_BEFORE_JOIN
= new HazelcastProperty("hazelcast.wait.seconds.before.join", 5, SECONDS);
public static final HazelcastProperty MAX_WAIT_SECONDS_BEFORE_JOIN
= new HazelcastProperty("hazelcast.max.wait.seconds.before.join", 20, SECONDS);
public static final HazelcastProperty MAX_JOIN_SECONDS
= new HazelcastProperty("hazelcast.max.join.seconds", 300, SECONDS);
public static final HazelcastProperty MAX_JOIN_MERGE_TARGET_SECONDS
= new HazelcastProperty("hazelcast.max.join.merge.target.seconds", 20, SECONDS);
/**
* The interval at which member heartbeat messages are sent
*/
public static final HazelcastProperty HEARTBEAT_INTERVAL_SECONDS
= new HazelcastProperty("hazelcast.heartbeat.interval.seconds", 5, SECONDS);
/**
* The timeout which defines when master candidate gives up waiting for response to its mastership claim.
* After timeout happens, non-responding member will be removed from member list.
*/
public static final HazelcastProperty MASTERSHIP_CLAIM_TIMEOUT_SECONDS
= new HazelcastProperty("hazelcast.mastership.claim.timeout.seconds", 120, SECONDS);
/**
* The timeout which defines when a cluster member is removed because it has not sent any heartbeats.
*/
public static final HazelcastProperty MAX_NO_HEARTBEAT_SECONDS
= new HazelcastProperty("hazelcast.max.no.heartbeat.seconds", 60, SECONDS);
/**
* The interval at which master confirmations are sent from non-master nodes to the master node
*
* @deprecated since 3.10
*/
@Deprecated
public static final HazelcastProperty MASTER_CONFIRMATION_INTERVAL_SECONDS
= new HazelcastProperty("hazelcast.master.confirmation.interval.seconds", 30, SECONDS);
/**
* The timeout which defines when a cluster member is removed because it has not sent any master confirmations.
*
* @deprecated since 3.10
*/
@Deprecated
public static final HazelcastProperty MAX_NO_MASTER_CONFIRMATION_SECONDS
= new HazelcastProperty("hazelcast.max.no.master.confirmation.seconds", 150, SECONDS);
/**
* Heartbeat failure detector type. Available options are:
* <ul>
* <li><code>deadline</code>: A deadline based failure detector uses an absolute timeout
* for missing/lost heartbeats. After timeout member is considered as dead/unavailable.
* </li>
* <li><code>phi-accrual</code>: Implementation of 'The Phi Accrual Failure Detector' by Hayashibara et al.
* as defined in their paper. Phi Accrual Failure Detector is adaptive to network/environment conditions,
* that's why a lower {@link #MAX_NO_HEARTBEAT_SECONDS} (for example 10 or 15 seconds) can be used to provide
* faster detection of unavailable members.
* </li>
* </ul>
*
* Default failure detector is <code>deadline</code>.
*/
public static final HazelcastProperty HEARTBEAT_FAILURE_DETECTOR_TYPE
= new HazelcastProperty("hazelcast.heartbeat.failuredetector.type", ClusterFailureDetectorType.DEADLINE.toString());
/**
* The interval at which the master sends the member lists are sent to other non-master members
*/
public static final HazelcastProperty MEMBER_LIST_PUBLISH_INTERVAL_SECONDS
= new HazelcastProperty("hazelcast.member.list.publish.interval.seconds", 60, SECONDS);
public static final HazelcastProperty CLIENT_HEARTBEAT_TIMEOUT_SECONDS
= new HazelcastProperty("hazelcast.client.max.no.heartbeat.seconds", 300, SECONDS);
public static final HazelcastProperty CLUSTER_SHUTDOWN_TIMEOUT_SECONDS
= new HazelcastProperty("hazelcast.cluster.shutdown.timeout.seconds", 900, SECONDS);
/**
* If a member should be pinged when a sufficient amount of heartbeats have passed and the member has not sent any
* heartbeats. If the member is not reachable, it will be removed.
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_ENABLED
= new HazelcastProperty("hazelcast.icmp.enabled", false);
/**
* Run ICMP detection in parallel with the Heartbeat failure detector.
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_PARALLEL_MODE
= new HazelcastProperty("hazelcast.icmp.parallel.mode", true);
/**
* Enforce ICMP Echo Request mode for ping-detector. If OS is not supported,
* or not configured correctly as per reference-manual, hazelcast will fail to start.
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_ECHO_FAIL_FAST
= new HazelcastProperty("hazelcast.icmp.echo.fail.fast.on.startup", true);
/**
* Ping timeout in milliseconds. This cannot be more than the interval value. Should always be smaller.
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_TIMEOUT
= new HazelcastProperty("hazelcast.icmp.timeout", 1000, MILLISECONDS);
/**
* Interval between ping attempts in milliseconds. Default and min allowed, 1 second.
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_INTERVAL
= new HazelcastProperty("hazelcast.icmp.interval", 1000, MILLISECONDS);
/**
* Max ping attempts before suspecting a member
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_MAX_ATTEMPTS
= new HazelcastProperty("hazelcast.icmp.max.attempts", 3);
/**
* Ping TTL, the maximum number of hops the packets should go through or 0 for the default.
* Zero in this case means unlimited hops.
*
* @deprecated as of 3.10 this can be configured through {@link com.hazelcast.config.IcmpFailureDetectorConfig}
* This will be removed in future versions. Until this is done,
* if the {@link com.hazelcast.config.IcmpFailureDetectorConfig} is null we will still fall back to this
*/
public static final HazelcastProperty ICMP_TTL
= new HazelcastProperty("hazelcast.icmp.ttl", 0);
public static final HazelcastProperty INITIAL_MIN_CLUSTER_SIZE
= new HazelcastProperty("hazelcast.initial.min.cluster.size", 0);
public static final HazelcastProperty INITIAL_WAIT_SECONDS
= new HazelcastProperty("hazelcast.initial.wait.seconds", 0, SECONDS);
/**
* The number of incremental ports, starting with port number defined in network configuration,
* that will be used to connect to a host which is defined without a port in the TCP-IP member list
* while a node is searching for a cluster.
*/
public static final HazelcastProperty TCP_JOIN_PORT_TRY_COUNT
= new HazelcastProperty("hazelcast.tcp.join.port.try.count", 3);
public static final HazelcastProperty MAP_REPLICA_SCHEDULED_TASK_DELAY_SECONDS
= new HazelcastProperty("hazelcast.map.replica.scheduled.task.delay.seconds", 10, SECONDS);
/**
* You can use MAP_EXPIRY_DELAY_SECONDS to deal with some possible
* edge cases, such as using EntryProcessor. Without this delay, you
* may see that an EntryProcessor running on the owner partition
* found a key, but EntryBackupProcessor did not find it on backup,
* and as a result when backup promotes to owner you will end up
* with an unprocessed key.
*/
public static final HazelcastProperty MAP_EXPIRY_DELAY_SECONDS
= new HazelcastProperty("hazelcast.map.expiry.delay.seconds", 10, SECONDS);
/**
* Maximum number of IMap entries Hazelcast will evict during a
* single eviction cycle. Eviction cycle is triggered by a map
* mutation. Typically it's OK to evict at most a single entry.
* However imagine the scenario where you are inserting values in a
* loop and in each iteration you double entry size. In this
* situation Hazelcast has to evict more than just a single entry -
* as all existing entries are smaller than the entry which is about
* to be added and removing any old entry cannot make sufficient
* room for the new entry.
*
* Default: 1
*/
public static final HazelcastProperty MAP_EVICTION_BATCH_SIZE
= new HazelcastProperty("hazelcast.map.eviction.batch.size", 1);
/**
* This property is a switch between old and new event publishing
* behavior of map#loadAll. When it is true, map#loadAll publishes
* entry ADDED events, when false, map#loadAll publishes entry
* LOADED events. By default LOADED events will be published.
*
* @since 3.11
*/
public static final HazelcastProperty MAP_LOAD_ALL_PUBLISHES_ADDED_EVENT
= new HazelcastProperty("hazelcast.map.loadAll.publishes.added.event", false);
public static final HazelcastProperty LOGGING_TYPE
= new HazelcastProperty("hazelcast.logging.type", "jdk");
public static final HazelcastProperty ENABLE_JMX
= new HazelcastProperty("hazelcast.jmx", false);
public static final HazelcastProperty JMX_UPDATE_INTERVAL_SECONDS
= new HazelcastProperty("hazelcast.jmx.update.interval.seconds", 5, SECONDS);
public static final HazelcastProperty MC_MAX_VISIBLE_SLOW_OPERATION_COUNT
= new HazelcastProperty("hazelcast.mc.max.visible.slow.operations.count", 10);
public static final HazelcastProperty MC_URL_CHANGE_ENABLED
= new HazelcastProperty("hazelcast.mc.url.change.enabled", true);
public static final HazelcastProperty CONNECTION_MONITOR_INTERVAL
= new HazelcastProperty("hazelcast.connection.monitor.interval", 100, MILLISECONDS);
public static final HazelcastProperty CONNECTION_MONITOR_MAX_FAULTS
= new HazelcastProperty("hazelcast.connection.monitor.max.faults", 3);
/**
* Time in seconds to sleep after a migration task.
*/
public static final HazelcastProperty PARTITION_MIGRATION_INTERVAL
= new HazelcastProperty("hazelcast.partition.migration.interval", 0, SECONDS);
/**
* Timeout in seconds for all migration operations.
*/
public static final HazelcastProperty PARTITION_MIGRATION_TIMEOUT
= new HazelcastProperty("hazelcast.partition.migration.timeout", 300, SECONDS);
public static final HazelcastProperty PARTITION_FRAGMENTED_MIGRATION_ENABLED
= new HazelcastProperty("hazelcast.partition.migration.fragments.enabled", true);
public static final HazelcastProperty DISABLE_STALE_READ_ON_PARTITION_MIGRATION
= new HazelcastProperty("hazelcast.partition.migration.stale.read.disabled", false);
public static final HazelcastProperty PARTITION_TABLE_SEND_INTERVAL
= new HazelcastProperty("hazelcast.partition.table.send.interval", 15, SECONDS);
public static final HazelcastProperty PARTITION_BACKUP_SYNC_INTERVAL
= new HazelcastProperty("hazelcast.partition.backup.sync.interval", 30, SECONDS);
public static final HazelcastProperty PARTITION_MAX_PARALLEL_REPLICATIONS
= new HazelcastProperty("hazelcast.partition.max.parallel.replications", 5);
public static final HazelcastProperty PARTITIONING_STRATEGY_CLASS
= new HazelcastProperty("hazelcast.partitioning.strategy.class", "");
public static final HazelcastProperty GRACEFUL_SHUTDOWN_MAX_WAIT
= new HazelcastProperty("hazelcast.graceful.shutdown.max.wait", 600, SECONDS);
/**
* Enables or disables the {@link com.hazelcast.spi.impl.operationexecutor.slowoperationdetector.SlowOperationDetector}.
*/
public static final HazelcastProperty SLOW_OPERATION_DETECTOR_ENABLED
= new HazelcastProperty("hazelcast.slow.operation.detector.enabled", true);
/**
* Defines a threshold above which a running operation in {@link com.hazelcast.spi.OperationService} is considered to be slow.
* These operations will log a warning and will be shown in the Management Center with detailed information, e.g. stacktrace.
*/
public static final HazelcastProperty SLOW_OPERATION_DETECTOR_THRESHOLD_MILLIS
= new HazelcastProperty("hazelcast.slow.operation.detector.threshold.millis", 10000, MILLISECONDS);
/**
* This value defines the retention time of invocations in slow operation logs.
* <p/>
* If an invocation is older than this value, it will be purged from the log to prevent unlimited memory usage.
* When all invocations are purged from a log, the log itself will be deleted.
*
* @see #SLOW_OPERATION_DETECTOR_LOG_PURGE_INTERVAL_SECONDS
*/
public static final HazelcastProperty SLOW_OPERATION_DETECTOR_LOG_RETENTION_SECONDS
= new HazelcastProperty("hazelcast.slow.operation.detector.log.retention.seconds", 3600, SECONDS);
/**
* Purge interval for slow operation logs.
*
* @see #SLOW_OPERATION_DETECTOR_LOG_RETENTION_SECONDS
*/
public static final HazelcastProperty SLOW_OPERATION_DETECTOR_LOG_PURGE_INTERVAL_SECONDS
= new HazelcastProperty("hazelcast.slow.operation.detector.log.purge.interval.seconds", 300, SECONDS);
/**
* Defines if the stacktraces of slow operations are logged in the log file. Stacktraces will always be reported to the
* Management Center, but by default they are not printed to keep the log size small.
*/
public static final HazelcastProperty SLOW_OPERATION_DETECTOR_STACK_TRACE_LOGGING_ENABLED
= new HazelcastProperty("hazelcast.slow.operation.detector.stacktrace.logging.enabled", false);
/**
* Property isn't used anymore.
*/
@Deprecated
public static final HazelcastProperty SLOW_INVOCATION_DETECTOR_THRESHOLD_MILLIS
= new HazelcastProperty("hazelcast.slow.invocation.detector.threshold.millis", -1, MILLISECONDS);
public static final HazelcastProperty LOCK_MAX_LEASE_TIME_SECONDS
= new HazelcastProperty("hazelcast.lock.max.lease.time.seconds", Long.MAX_VALUE, SECONDS);
public static final HazelcastProperty ENTERPRISE_LICENSE_KEY
= new HazelcastProperty("hazelcast.enterprise.license.key");
/**
* Setting this capacity is valid if you set {@link com.hazelcast.config.MapStoreConfig#writeCoalescing} to {@code false}.
* Otherwise its value will not be taken into account.
* <p/>
* The per node maximum write-behind queue capacity is the total of all write-behind queue sizes in a node, including backups.
* <p/>
* The maximum value which can be set is {@link Integer#MAX_VALUE}
*/
public static final HazelcastProperty MAP_WRITE_BEHIND_QUEUE_CAPACITY
= new HazelcastProperty("hazelcast.map.write.behind.queue.capacity", 50000);
/**
* Defines cache invalidation event batch sending is enabled or not.
*/
public static final HazelcastProperty CACHE_INVALIDATION_MESSAGE_BATCH_ENABLED
= new HazelcastProperty("hazelcast.cache.invalidation.batch.enabled", true);
/**
* Defines the maximum number of cache invalidation events to be drained and sent to the event listeners in a batch.
*/
public static final HazelcastProperty CACHE_INVALIDATION_MESSAGE_BATCH_SIZE
= new HazelcastProperty("hazelcast.cache.invalidation.batch.size", 100);
/**
* Defines the cache invalidation event batch sending frequency in seconds.
* <p/>
* When the number of events do not come up to {@link #CACHE_INVALIDATION_MESSAGE_BATCH_SIZE} in the given time period (which
* is defined by this property); those events are gathered into a batch and sent to target.
*/
public static final HazelcastProperty CACHE_INVALIDATION_MESSAGE_BATCH_FREQUENCY_SECONDS
= new HazelcastProperty("hazelcast.cache.invalidation.batchfrequency.seconds", 10, SECONDS);
/**
* Defines Near Cache invalidation event batch sending is enabled or not.
*/
public static final HazelcastProperty MAP_INVALIDATION_MESSAGE_BATCH_ENABLED
= new HazelcastProperty("hazelcast.map.invalidation.batch.enabled", true);
/**
* Defines the maximum number of Near Cache invalidation events to be drained and sent to the event Near Cache in a batch.
*/
public static final HazelcastProperty MAP_INVALIDATION_MESSAGE_BATCH_SIZE
= new HazelcastProperty("hazelcast.map.invalidation.batch.size", 100);
/**
* Defines the Near Cache invalidation event batch sending frequency in seconds.
* <p/>
* When the number of events do not come up to {@link #MAP_INVALIDATION_MESSAGE_BATCH_SIZE} in the given time period (which
* is defined by this property); those events are gathered into a batch and sent to target.
*/
public static final HazelcastProperty MAP_INVALIDATION_MESSAGE_BATCH_FREQUENCY_SECONDS
= new HazelcastProperty("hazelcast.map.invalidation.batchfrequency.seconds", 10, SECONDS);
/**
* Using back pressure, you can prevent an overload of pending asynchronous backups. With a map with a
* single asynchronous backup, producing asynchronous backups could happen at a higher rate than
* the consumption of the backup. This can eventually lead to an OOME (especially if the backups are slow).
* <p/>
* With back-pressure enabled, this can't happen.
* <p/>
* Back pressure is implemented by making asynchronous backups operations synchronous. This prevents the internal queues from
* overflowing because the invoker will wait for the primary and for the backups to complete. The frequency of this is
* determined by the sync-window.
*
* To deal with overloads of backups, the property 'hazelcast.operation.backup.timeout.millis' should be set to a larger
* value; above 60000 is recommended. Otherwise it can still happen backups accumulate.
*/
public static final HazelcastProperty BACKPRESSURE_ENABLED
= new HazelcastProperty("hazelcast.backpressure.enabled", false);
/**
* Controls the frequency of a BackupAwareOperation getting its async backups converted to a sync backups. This is needed
* to prevent an accumulation of asynchronous backups and eventually running into stability issues.
* <p/>
* A sync window of 10 means that 1 in 10 BackupAwareOperations get their async backups convert to sync backups.
* <p/>
* A sync window of 1 means that every BackupAwareOperation get their async backups converted to sync backups. 1
* is also the smallest legal value for the sync window.
* <p/>
* There is some randomization going on to prevent resonance. Therefore, with a sync window of n, not every Nth
* BackupAwareOperation operation gets its async backups converted to sync.
* <p/>
* This property only has meaning when backpressure is enabled.
*/
public static final HazelcastProperty BACKPRESSURE_SYNCWINDOW
= new HazelcastProperty("hazelcast.backpressure.syncwindow", 100);
/**
* Control the maximum timeout in millis to wait for an invocation space to be available.
* <p/>
* If an invocation can't be made because there are too many pending invocations, then an exponential backoff is done
* to give the system time to deal with the backlog of invocations. This property controls how long an invocation is
* allowed to wait before getting a {@link com.hazelcast.core.HazelcastOverloadException}.
* <p/>
* The value needs to be equal or larger than 0.
*/
public static final HazelcastProperty BACKPRESSURE_BACKOFF_TIMEOUT_MILLIS
= new HazelcastProperty("hazelcast.backpressure.backoff.timeout.millis", 60000, MILLISECONDS);
/**
* The maximum number of concurrent invocations per partition.
* <p/>
* To prevent the system from overloading, HZ can apply a constraint on the number of concurrent invocations. If the maximum
* number of concurrent invocations has been exceeded and a new invocation comes in, then an exponential back-off is applied
* till eventually a timeout happens or there is room for the invocation.
* <p/>
* By default it is configured as 100. With 271 partitions, that would give (271 + 1) * 100 = 27200 concurrent invocations
* from a single member. The +1 is for generic operations. The reasons why 100 is chosen are:
* - there can be concurrent operations that touch a lot of partitions which consume more than 1 invocation, and
* - certain methods like those from the IExecutor or ILock are also invocations and they can be very long running.
* <p/>
* No promise is made for the invocations being tracked per partition, or if there is a general pool of invocations.
*/
public static final HazelcastProperty BACKPRESSURE_MAX_CONCURRENT_INVOCATIONS_PER_PARTITION
= new HazelcastProperty("hazelcast.backpressure.max.concurrent.invocations.per.partition", 100);
/**
* Run Query Evaluations for multiple partitions in parallel.
* <p/>
* Each Hazelcast member evaluates query predicates using a single thread by default. In most cases the overhead of
* inter-thread communication overweight benefit of parallel execution.
* <p/>
* When you have a large dataset and/or slow predicate you may benefit from parallel predicate evaluations.
* Set to true if you are using slow predicates or have > 100,000s entries per member.
* <p/>
* The default is false.
*/
public static final HazelcastProperty QUERY_PREDICATE_PARALLEL_EVALUATION
= new HazelcastProperty("hazelcast.query.predicate.parallel.evaluation", false);
/**
* Run aggregation accumulation for multiple entries in parallel.
* <p/>
* Each Hazelcast member executes the accumulation stage of an aggregation using a single thread by default.
* In most cases it pays off to do it in parallel.
* <p/>
* The default is true.
*/
public static final HazelcastProperty AGGREGATION_ACCUMULATION_PARALLEL_EVALUATION
= new HazelcastProperty("hazelcast.aggregation.accumulation.parallel.evaluation", true);
/**
* Result size limit for query operations on maps.
* <p/>
* This value defines the maximum number of returned elements for a single query result. If a query exceeds this number of
* elements, a {@link QueryResultSizeExceededException} will be thrown.
* <p/>
* This feature prevents an OOME if a single node is requesting the whole data set of the cluster, such as by
* executing a query with {@link TruePredicate}. This applies internally for the {@link IMap#values()}, {@link IMap#keySet()}
* and {@link IMap#entrySet()} methods, which are good candidates for OOME in large clusters.
* <p/>
* This feature depends on an equal distribution of the data on the cluster nodes to calculate the result size limit per node.
* Therefore, there is a minimum value of {@value QueryResultSizeLimiter#MINIMUM_MAX_RESULT_LIMIT} defined in
* {@link QueryResultSizeLimiter}. Configured values below the minimum will be increased to the minimum.
* <p/>
* The feature can be disabled by setting its value to <tt>-1</tt> (which is the default value).
*/
public static final HazelcastProperty QUERY_RESULT_SIZE_LIMIT
= new HazelcastProperty("hazelcast.query.result.size.limit", -1);
/**
* Maximum value of local partitions to trigger local pre-check for {@link TruePredicate} query operations on maps.
* <p/>
* To limit the result size of a query ({@see PROP_QUERY_RESULT_SIZE_LIMIT}); a local pre-check on the requesting node can be
* done before the query is sent to the cluster. Since this may increase the latency, the pre-check is limited to a maximum
* number of local partitions.
* <p/>
* By increasing this parameter, you can prevent the execution of the query on the cluster. Increasing this parameter
* increases the latency due to the prolonged local pre-check.
* <p/>
* The pre-check can be disabled by setting the value to <tt>-1</tt>.
*
* @see #QUERY_RESULT_SIZE_LIMIT
*/
public static final HazelcastProperty QUERY_MAX_LOCAL_PARTITION_LIMIT_FOR_PRE_CHECK
= new HazelcastProperty("hazelcast.query.max.local.partition.limit.for.precheck", 3);
/**
* Type of Query Optimizer.
* Valid Values:
* <ul>
* <li>RULES - for optimizations based on static rules</li>
* <li>NONE - optimization are disabled</li>
* </ul>
* <p/>
* Values are case sensitive
*/
public static final HazelcastProperty QUERY_OPTIMIZER_TYPE
= new HazelcastProperty("hazelcast.query.optimizer.type", QueryOptimizerFactory.Type.RULES.toString());
/**
* Type of Query Index result copying behavior.
*
* Defines the behavior for index copying on index read/write.
*
* Supported in BINARY and OBJECT in-memory-formats. Ignored in NATIVE in-memory-format.
*
* Why is it needed? In order to support correctness the internal data-structures used by indexes need to do some copying.
* The copying may take place on-read or on-write:
*
* -> Copying on-read means that each index-read operation will copy the result of the query before returning it to the
* caller.This copying may be expensive, depending on the size of the result, since the result is stored in a map, which
* means that all entries need to have the hash calculated before being stored in a bucket.
* Each index-write operation however will be fast, since there will be no copying taking place.
*
* -> Copying on-write means that each index-write operation will completely copy the underlying map to provide the
* copy-on-write semantics. Depending on the index size, it may be a very expensive operation.
* Each index-read operation will be very fast, however, since it may just access the map and return it to the caller.
*
* -> Never copying is tricky. It means that the internal data structures of the index are concurrently modified without
* copy-on-write semantics. Index reads never copy the results of a query to a separate map.
* It means that the results backed by the underlying index-map can change after the query has been executed.
* Specifically an entry might have been added / removed from an index, or it might have been remapped.
* Should be used in cases when a the caller expects "mostly correct" results - specifically, if it's ok
* if some entries returned in the result set do not match the initial query criteria.
* The fastest solution for read and writes, since no copying takes place.
*
* It's a tuneable trade-off - the user may decide.
*
* Valid Values:
* <ul>
* <li>COPY_ON_READY - Internal data structures of the index are concurrently modified without copy-on-write semantics.
* Index queries copy the results of a query on index read to detach the result from the source map.
* Should be used in index-write intensive cases, since the reads will slow down due to the copying.
* Default value.
* </li>
* <li>COPY_ON_WRITE - Internal data structures of the index are modified with copy-on-write semantics.
* Previously returned index query results reflect the state of the index at the time of the query and are not
* affected by future index modifications.
* Should be used in index-read intensive cases, since the writes will slow down due to the copying.
* </li>
* <li>NEVER - Internal data structures of the index are concurrently modified without copy-on-write semantics.
* Index reads never copy the results of a query to a separate map.
* It means that the results backed by the underlying index-map can change after the query has been executed.
* Specifically an entry might have been added / removed from an index, or it might have been remapped.
* Should be used in cases when a the caller expects "mostly correct" results - specifically, if it's ok
* if some entries returned in the result set do not match the initial query criteria.
* The fastest solution for read and writes, since no copying takes place.</li>
* </ul>
* <p/>
*/
public static final HazelcastProperty INDEX_COPY_BEHAVIOR
= new HazelcastProperty("hazelcast.index.copy.behavior", IndexCopyBehavior.COPY_ON_READ.toString());
/**
* Forces the JCache provider, which can have values client or server, to force the provider type.
* If not provided, the provider will be client or server, whichever is found on the classpath first respectively.
*/
public static final HazelcastProperty JCACHE_PROVIDER_TYPE
= new HazelcastProperty("hazelcast.jcache.provider.type");
/**
* <p>Enables the Discovery SPI lookup over the old native implementations. This property is temporary and will
* eventually be removed when the experimental marker is removed.</p>
* <p>Discovery SPI is <b>disabled</b> by default</p>
*/
public static final HazelcastProperty DISCOVERY_SPI_ENABLED
= new HazelcastProperty("hazelcast.discovery.enabled", false);
/**
* <p>Enables the Discovery Joiner to use public ips from DiscoveredNode. This property is temporary and will
* eventually be removed when the experimental marker is removed.</p>
* <p>Discovery SPI is <b>disabled</b> by default</p>
*/
public static final HazelcastProperty DISCOVERY_SPI_PUBLIC_IP_ENABLED
= new HazelcastProperty("hazelcast.discovery.public.ip.enabled", false);
/**
* When this property is true, if the server can not determine the connected client version, it shall assume that it is of
* 3.6.x version client. This property is especially needed if you are using ICache (or JCache).
*/
public static final HazelcastProperty COMPATIBILITY_3_6_CLIENT_ENABLED
= new HazelcastProperty("hazelcast.compatibility.3.6.client", false);
/**
* Hazelcast serialization version. This is single byte value between 1 and Max supported serialization version.
*
* @see BuildInfo#getSerializationVersion()
*/
public static final HazelcastProperty SERIALIZATION_VERSION
= new HazelcastProperty("hazelcast.serialization.version",
BuildInfoProvider.getBuildInfo().getSerializationVersion());
/**
* Override cluster version to use while node is not yet member of a cluster. The cluster version assumed before joining
* a cluster may affect the serialization format of cluster discovery & join operations and its compatibility with members
* of a cluster running on different Hazelcast codebase versions. The default is to use the node's codebase version. You may
* need to override it for your node to join a cluster running on a previous cluster version.
*/
public static final HazelcastProperty INIT_CLUSTER_VERSION
= new HazelcastProperty("hazelcast.init.cluster.version");
/**
* Enables legacy (pre-3.9) member list format which is printed in logs. New format is introduced by 3.9
* includes member list version.
*/
public static final HazelcastProperty USE_LEGACY_MEMBER_LIST_FORMAT
= new HazelcastProperty("hazelcast.legacy.memberlist.format.enabled", false);
/**
* Controls whether we apply more strict checks upon BIND requests towards a cluster member.
* The checks mainly validate the remote BIND request against the remote address as found in the socket.
* By default they are disabled, to avoid connectivity issues when deployed under NAT'ed infrastructure.
*/
public static final HazelcastProperty BIND_SPOOFING_CHECKS =
new HazelcastProperty("hazelcast.nio.tcp.spoofing.checks", false);
/**
* This is a Java 6 specific property. In Java 7+ tasks are always removed
* on cancellation due to the explicit
* {@code java.util.concurrent.ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)}
* and constant time removal.
*
* In Java 6 there is no out-of-the-box support for removal of cancelled tasks,
* and the only way to implement this is using a linear scan of all pending
* tasks. Therefore in Java 6 there is a performance penalty.
*
* Using this property, in Java 6, one can control if cancelled tasks are removed.
* By default tasks are removed, because it can lead to temporary retention
* of memory if there a large volume of pending cancelled tasks. And this can
* lead to gc/performance problems as we saw with the transaction tests.
*
* However if this automatic removal of cancelled tasks start to become a
* performance problem, it can be disabled in Java 6.
*
* For more information see the {@link com.hazelcast.util.executor.LoggingScheduledExecutor}.
*/
public static final HazelcastProperty TASK_SCHEDULER_REMOVE_ON_CANCEL =
new HazelcastProperty("hazelcast.executionservice.taskscheduler.remove.oncancel", true);
/**
* By default, search for data structures config is performed within static configuration first:
* <ul>
* <li>Exact match in static config</li>
* <li>Wildcard match in static config</li>
* <li>Exact match in dynamic config</li>
* <li>Wildcard match in dynamic config</li>
* <li>Fallback to default</li>
* </ul>
* But sometimes it makes sense to perform search within dynamic configs first. If this property is set to
* <code>true</code>, search algorithm changes to:
* <ul>
* <li>Exact match in dynamic config</li>
* <li>Wildcard match in dynamic config</li>
* <li>Exact match in static config</li>
* <li>Wildcard match in static config</li>
* <li>Fallback to default</li>
* </ul>
*/
public static final HazelcastProperty SEARCH_DYNAMIC_CONFIG_FIRST
= new HazelcastProperty("hazelcast.data.search.dynamic.config.first.enabled", false);
private GroupProperty() {
}
}
| {
"content_hash": "8508bfd4a64bf7a95b47b0da4e29326e",
"timestamp": "",
"source": "github",
"line_count": 1012,
"max_line_length": 130,
"avg_line_length": 54.23122529644269,
"alnum_prop": 0.7162457636383514,
"repo_name": "tufangorel/hazelcast",
"id": "f1cda6ee3372b3e77c4c33c8883296167e47c9ec",
"size": "55507",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hazelcast/src/main/java/com/hazelcast/spi/properties/GroupProperty.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1474"
},
{
"name": "C",
"bytes": "344"
},
{
"name": "Java",
"bytes": "40012801"
},
{
"name": "Shell",
"bytes": "15202"
}
],
"symlink_target": ""
} |
package com.gcit.lms.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import com.gcit.lms.entity.BookLoan;
public class BookLoanDAO extends BaseDAO implements ResultSetExtractor<List<BookLoan>> {
public List<BookLoan> readBookLoans(Integer branchId, Integer borrowerId) throws Exception {
return template.query("select * from tbl_book_loans where branchId = ? and cardNo = ?",
new Object[] { branchId, borrowerId }, this);
}
public BookLoan readBookLoan(Integer branchId, Integer borrowerId, Integer bookId) {
List<BookLoan> bls = template.query(
"select * from tbl_book_loans where branchId = ? and cardNo = ? and bookId = ?",
new Object[] { branchId, borrowerId, bookId }, this);
if (bls != null && !bls.isEmpty()) {
return bls.get(0);
}
return null;
}
public List<BookLoan> readBookLoansAtBranch(Integer branchId) {
return template.query("select * from tbl_book_loans where branchId = ?", new Object[] { branchId }, this);
}
public void updateBookLoanDueDate(BookLoan bl) {
if (readBookLoan(bl.getBranchId(), bl.getCardNo(), bl.getBookId()) == null)
return;
else
template.update("update tbl_book_loans set dueDate = ? where bookId = ? and branchId = ? and cardNo = ?",
new Object[] { bl.getDueDate(), bl.getBookId(), bl.getBranchId(), bl.getCardNo() });
}
public void extendDueDate(Integer branchId, Integer bookId, Integer cardNo) {
template.update(
"update tbl_book_loans set dueDate = DATE_ADD(dueDate, INTERVAL 1 DAY) where branchId = ? and bookId = ? and cardNo = ?",
new Object[] { branchId, bookId, cardNo });
}
@Override
public List<BookLoan> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<BookLoan> bookloans = new ArrayList<>();
while (rs.next()) {
BookLoan bl = new BookLoan();
bl.setBookId(rs.getInt("bookId"));
bl.setBranchId(rs.getInt("branchId"));
bl.setCardNo(rs.getInt("cardNo"));
bl.setDateOut(rs.getDate("dateOut"));
bl.setDueDate(rs.getDate("dueDate"));
if (rs.getDate("dateIn") != null)
bl.setDateIn(rs.getDate("dateIn"));
bookloans.add(bl);
}
return bookloans;
}
}
| {
"content_hash": "95d103aea9a18547ba906740f2c980e7",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 125,
"avg_line_length": 35.41538461538462,
"alnum_prop": 0.7072111207645526,
"repo_name": "yikaicao/LMSRESTful",
"id": "98950290f3ddbab96a28a62eb060180ca8bba029",
"size": "2302",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LMSSpring/src/main/java/com/gcit/lms/dao/BookLoanDAO.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "688"
},
{
"name": "HTML",
"bytes": "36220"
},
{
"name": "Java",
"bytes": "51456"
},
{
"name": "JavaScript",
"bytes": "28723"
}
],
"symlink_target": ""
} |
namespace extensions {
class ScriptContext;
// Utility for logging console messages.
namespace console {
// Adds |message| to the console of of the |script_context|. If |script_context|
// is null, LOG()s the message instead.
void AddMessage(ScriptContext* script_context,
blink::mojom::ConsoleMessageLevel level,
const std::string& message);
// Logs an Error then crashes the current process.
void Fatal(ScriptContext* context, const std::string& message);
// Returns a new v8::Object with each standard log method (Debug/Log/Warn/Error)
// bound to respective debug/log/warn/error methods. This is a direct drop-in
// replacement for the standard devtools console.* methods usually accessible
// from JS.
v8::Local<v8::Object> AsV8Object(v8::Isolate* isolate);
} // namespace console
} // namespace extensions
#endif // EXTENSIONS_RENDERER_CONSOLE_H_
| {
"content_hash": "a71e89e5b79fbbb0f7405f7c3ded9967",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 80,
"avg_line_length": 34.42307692307692,
"alnum_prop": 0.7284916201117319,
"repo_name": "nwjs/chromium.src",
"id": "c20352c10e9710b102701b5243cb9e3b055a0cff",
"size": "1248",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "extensions/renderer/console.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.amazonaws.services.ec2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* DeleteTransitGatewayRouteTableAnnouncementRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteTransitGatewayRouteTableAnnouncementRequestMarshaller implements
Marshaller<Request<DeleteTransitGatewayRouteTableAnnouncementRequest>, DeleteTransitGatewayRouteTableAnnouncementRequest> {
public Request<DeleteTransitGatewayRouteTableAnnouncementRequest> marshall(
DeleteTransitGatewayRouteTableAnnouncementRequest deleteTransitGatewayRouteTableAnnouncementRequest) {
if (deleteTransitGatewayRouteTableAnnouncementRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DeleteTransitGatewayRouteTableAnnouncementRequest> request = new DefaultRequest<DeleteTransitGatewayRouteTableAnnouncementRequest>(
deleteTransitGatewayRouteTableAnnouncementRequest, "AmazonEC2");
request.addParameter("Action", "DeleteTransitGatewayRouteTableAnnouncement");
request.addParameter("Version", "2016-11-15");
request.setHttpMethod(HttpMethodName.POST);
if (deleteTransitGatewayRouteTableAnnouncementRequest.getTransitGatewayRouteTableAnnouncementId() != null) {
request.addParameter("TransitGatewayRouteTableAnnouncementId",
StringUtils.fromString(deleteTransitGatewayRouteTableAnnouncementRequest.getTransitGatewayRouteTableAnnouncementId()));
}
return request;
}
}
| {
"content_hash": "6c3fc6cba9a6b1f8e80765f667f29ad8",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 147,
"avg_line_length": 43.651162790697676,
"alnum_prop": 0.7927543953116676,
"repo_name": "aws/aws-sdk-java",
"id": "cbf811542a1ef54700f0744da2eeab094240bb49",
"size": "2457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DeleteTransitGatewayRouteTableAnnouncementRequestMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.hadoop.hbase.replication;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp;
import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.BadVersionException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.KeeperException.NotEmptyException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils;
/**
* ZK based replication queue storage.
* <p>
* The base znode for each regionserver is the regionserver name. For example:
*
* <pre>
* /hbase/replication/rs/hostname.example.org,6020,1234
* </pre>
*
* Within this znode, the region server maintains a set of WAL replication queues. These queues are
* represented by child znodes named using there give queue id. For example:
*
* <pre>
* /hbase/replication/rs/hostname.example.org,6020,1234/1
* /hbase/replication/rs/hostname.example.org,6020,1234/2
* </pre>
*
* Each queue has one child znode for every WAL that still needs to be replicated. The value of
* these WAL child znodes is the latest position that has been replicated. This position is updated
* every time a WAL entry is replicated. For example:
*
* <pre>
* /hbase/replication/rs/hostname.example.org,6020,1234/1/23522342.23422 [VALUE: 254]
* </pre>
*/
@InterfaceAudience.Private
class ZKReplicationQueueStorage extends ZKReplicationStorageBase
implements ReplicationQueueStorage {
private static final Logger LOG = LoggerFactory.getLogger(ZKReplicationQueueStorage.class);
public static final String ZOOKEEPER_ZNODE_REPLICATION_HFILE_REFS_KEY =
"zookeeper.znode.replication.hfile.refs";
public static final String ZOOKEEPER_ZNODE_REPLICATION_HFILE_REFS_DEFAULT = "hfile-refs";
public static final String ZOOKEEPER_ZNODE_REPLICATION_REGIONS_KEY =
"zookeeper.znode.replication.regions";
public static final String ZOOKEEPER_ZNODE_REPLICATION_REGIONS_DEFAULT = "regions";
/**
* The name of the znode that contains all replication queues
*/
private final String queuesZNode;
/**
* The name of the znode that contains queues of hfile references to be replicated
*/
private final String hfileRefsZNode;
@VisibleForTesting
final String regionsZNode;
public ZKReplicationQueueStorage(ZKWatcher zookeeper, Configuration conf) {
super(zookeeper, conf);
String queuesZNodeName = conf.get("zookeeper.znode.replication.rs", "rs");
String hfileRefsZNodeName = conf.get(ZOOKEEPER_ZNODE_REPLICATION_HFILE_REFS_KEY,
ZOOKEEPER_ZNODE_REPLICATION_HFILE_REFS_DEFAULT);
this.queuesZNode = ZNodePaths.joinZNode(replicationZNode, queuesZNodeName);
this.hfileRefsZNode = ZNodePaths.joinZNode(replicationZNode, hfileRefsZNodeName);
this.regionsZNode = ZNodePaths.joinZNode(replicationZNode, conf
.get(ZOOKEEPER_ZNODE_REPLICATION_REGIONS_KEY, ZOOKEEPER_ZNODE_REPLICATION_REGIONS_DEFAULT));
}
@Override
public String getRsNode(ServerName serverName) {
return ZNodePaths.joinZNode(queuesZNode, serverName.getServerName());
}
private String getQueueNode(ServerName serverName, String queueId) {
return ZNodePaths.joinZNode(getRsNode(serverName), queueId);
}
private String getFileNode(String queueNode, String fileName) {
return ZNodePaths.joinZNode(queueNode, fileName);
}
private String getFileNode(ServerName serverName, String queueId, String fileName) {
return getFileNode(getQueueNode(serverName, queueId), fileName);
}
/**
* <p>
* Put all regions under /hbase/replication/regions znode will lead to too many children because
* of the huge number of regions in real production environment. So here we will distribute the
* znodes to multiple directories.
* </p>
* <p>
* So the final znode path will be format like this:
*
* <pre>
* /hbase/replication/regions/dd/04/e76a6966d4ffa908ed0586764767-100
* </pre>
*
* Here the full encoded region name is dd04e76a6966d4ffa908ed0586764767, and we use the first two
* characters 'dd' as the first level directory name, and use the next two characters '04' as the
* second level directory name, and the rest part as the prefix of the znode, and the suffix '100'
* is the peer id.
* </p>
* @param encodedRegionName the encoded region name.
* @param peerId peer id for replication.
* @return ZNode path to persist the max sequence id that we've pushed for the given region and
* peer.
*/
@VisibleForTesting
String getSerialReplicationRegionPeerNode(String encodedRegionName, String peerId) {
if (encodedRegionName == null || encodedRegionName.length() != RegionInfo.MD5_HEX_LENGTH) {
throw new IllegalArgumentException(
"Invalid encoded region name: " + encodedRegionName + ", length should be 32.");
}
return new StringBuilder(regionsZNode).append(ZNodePaths.ZNODE_PATH_SEPARATOR)
.append(encodedRegionName.substring(0, 2)).append(ZNodePaths.ZNODE_PATH_SEPARATOR)
.append(encodedRegionName.substring(2, 4)).append(ZNodePaths.ZNODE_PATH_SEPARATOR)
.append(encodedRegionName.substring(4)).append("-").append(peerId).toString();
}
@Override
public void removeQueue(ServerName serverName, String queueId) throws ReplicationException {
try {
ZKUtil.deleteNodeRecursively(zookeeper, getQueueNode(serverName, queueId));
} catch (KeeperException e) {
throw new ReplicationException(
"Failed to delete queue (serverName=" + serverName + ", queueId=" + queueId + ")", e);
}
}
@Override
public void addWAL(ServerName serverName, String queueId, String fileName)
throws ReplicationException {
try {
ZKUtil.createWithParents(zookeeper, getFileNode(serverName, queueId, fileName));
} catch (KeeperException e) {
throw new ReplicationException("Failed to add wal to queue (serverName=" + serverName
+ ", queueId=" + queueId + ", fileName=" + fileName + ")", e);
}
}
@Override
public void removeWAL(ServerName serverName, String queueId, String fileName)
throws ReplicationException {
String fileNode = getFileNode(serverName, queueId, fileName);
try {
ZKUtil.deleteNode(zookeeper, fileNode);
} catch (NoNodeException e) {
LOG.warn("{} already deleted when removing log", fileNode);
} catch (KeeperException e) {
throw new ReplicationException("Failed to remove wal from queue (serverName=" + serverName +
", queueId=" + queueId + ", fileName=" + fileName + ")", e);
}
}
private void addLastSeqIdsToOps(String queueId, Map<String, Long> lastSeqIds,
List<ZKUtilOp> listOfOps) throws KeeperException, ReplicationException {
String peerId = new ReplicationQueueInfo(queueId).getPeerId();
for (Entry<String, Long> lastSeqEntry : lastSeqIds.entrySet()) {
String path = getSerialReplicationRegionPeerNode(lastSeqEntry.getKey(), peerId);
Pair<Long, Integer> p = getLastSequenceIdWithVersion(lastSeqEntry.getKey(), peerId);
byte[] data = ZKUtil.positionToByteArray(lastSeqEntry.getValue());
if (p.getSecond() < 0) { // ZNode does not exist.
ZKUtil.createWithParents(zookeeper,
path.substring(0, path.lastIndexOf(ZNodePaths.ZNODE_PATH_SEPARATOR)));
listOfOps.add(ZKUtilOp.createAndFailSilent(path, data));
continue;
}
// Perform CAS in a specific version v0 (HBASE-20138)
int v0 = p.getSecond();
long lastPushedSeqId = p.getFirst();
if (lastSeqEntry.getValue() <= lastPushedSeqId) {
continue;
}
listOfOps.add(ZKUtilOp.setData(path, data, v0));
}
}
@Override
public void setWALPosition(ServerName serverName, String queueId, String fileName, long position,
Map<String, Long> lastSeqIds) throws ReplicationException {
try {
for (int retry = 0;; retry++) {
List<ZKUtilOp> listOfOps = new ArrayList<>();
if (position > 0) {
listOfOps.add(ZKUtilOp.setData(getFileNode(serverName, queueId, fileName),
ZKUtil.positionToByteArray(position)));
}
// Persist the max sequence id(s) of regions for serial replication atomically.
addLastSeqIdsToOps(queueId, lastSeqIds, listOfOps);
if (listOfOps.isEmpty()) {
return;
}
try {
ZKUtil.multiOrSequential(zookeeper, listOfOps, false);
return;
} catch (KeeperException.BadVersionException | KeeperException.NodeExistsException e) {
LOG.warn(
"Bad version(or node exist) when persist the last pushed sequence id to zookeeper "
+ "storage, Retry = " + retry + ", serverName=" + serverName + ", queueId="
+ queueId + ", fileName=" + fileName);
}
}
} catch (KeeperException e) {
throw new ReplicationException("Failed to set log position (serverName=" + serverName
+ ", queueId=" + queueId + ", fileName=" + fileName + ", position=" + position + ")", e);
}
}
/**
* Return the {lastPushedSequenceId, ZNodeDataVersion} pair. if ZNodeDataVersion is -1, it means
* that the ZNode does not exist.
*/
@VisibleForTesting
protected Pair<Long, Integer> getLastSequenceIdWithVersion(String encodedRegionName,
String peerId) throws KeeperException {
Stat stat = new Stat();
String path = getSerialReplicationRegionPeerNode(encodedRegionName, peerId);
byte[] data = ZKUtil.getDataNoWatch(zookeeper, path, stat);
if (data == null) {
// ZNode does not exist, so just return version -1 to indicate that no node exist.
return Pair.newPair(HConstants.NO_SEQNUM, -1);
}
try {
return Pair.newPair(ZKUtil.parseWALPositionFrom(data), stat.getVersion());
} catch (DeserializationException de) {
LOG.warn("Failed to parse log position (region=" + encodedRegionName + ", peerId=" + peerId
+ "), data=" + Bytes.toStringBinary(data));
}
return Pair.newPair(HConstants.NO_SEQNUM, stat.getVersion());
}
@Override
public long getLastSequenceId(String encodedRegionName, String peerId)
throws ReplicationException {
try {
return getLastSequenceIdWithVersion(encodedRegionName, peerId).getFirst();
} catch (KeeperException e) {
throw new ReplicationException("Failed to get last pushed sequence id (encodedRegionName="
+ encodedRegionName + ", peerId=" + peerId + ")", e);
}
}
@Override
public void setLastSequenceIds(String peerId, Map<String, Long> lastSeqIds)
throws ReplicationException {
try {
// No need CAS and retry here, because it'll call setLastSequenceIds() for disabled peers
// only, so no conflict happen.
List<ZKUtilOp> listOfOps = new ArrayList<>();
for (Entry<String, Long> lastSeqEntry : lastSeqIds.entrySet()) {
String path = getSerialReplicationRegionPeerNode(lastSeqEntry.getKey(), peerId);
ZKUtil.createWithParents(zookeeper, path);
listOfOps.add(ZKUtilOp.setData(path, ZKUtil.positionToByteArray(lastSeqEntry.getValue())));
}
if (!listOfOps.isEmpty()) {
ZKUtil.multiOrSequential(zookeeper, listOfOps, true);
}
} catch (KeeperException e) {
throw new ReplicationException("Failed to set last sequence ids, peerId=" + peerId
+ ", size of lastSeqIds=" + lastSeqIds.size(), e);
}
}
@Override
public void removeLastSequenceIds(String peerId) throws ReplicationException {
String suffix = "-" + peerId;
try {
StringBuilder sb = new StringBuilder(regionsZNode);
int regionsZNodeLength = regionsZNode.length();
int levelOneLength = regionsZNodeLength + 3;
int levelTwoLength = levelOneLength + 3;
List<String> levelOneDirs = ZKUtil.listChildrenNoWatch(zookeeper, regionsZNode);
// it is possible that levelOneDirs is null if we haven't write any last pushed sequence ids
// yet, so we need an extra check here.
if (CollectionUtils.isEmpty(levelOneDirs)) {
return;
}
for (String levelOne : levelOneDirs) {
sb.append(ZNodePaths.ZNODE_PATH_SEPARATOR).append(levelOne);
for (String levelTwo : ZKUtil.listChildrenNoWatch(zookeeper, sb.toString())) {
sb.append(ZNodePaths.ZNODE_PATH_SEPARATOR).append(levelTwo);
for (String znode : ZKUtil.listChildrenNoWatch(zookeeper, sb.toString())) {
if (znode.endsWith(suffix)) {
sb.append(ZNodePaths.ZNODE_PATH_SEPARATOR).append(znode);
ZKUtil.deleteNode(zookeeper, sb.toString());
sb.setLength(levelTwoLength);
}
}
sb.setLength(levelOneLength);
}
sb.setLength(regionsZNodeLength);
}
} catch (KeeperException e) {
throw new ReplicationException("Failed to remove all last sequence ids, peerId=" + peerId, e);
}
}
@Override
public void removeLastSequenceIds(String peerId, List<String> encodedRegionNames)
throws ReplicationException {
try {
List<ZKUtilOp> listOfOps =
encodedRegionNames.stream().map(n -> getSerialReplicationRegionPeerNode(n, peerId))
.map(ZKUtilOp::deleteNodeFailSilent).collect(Collectors.toList());
ZKUtil.multiOrSequential(zookeeper, listOfOps, true);
} catch (KeeperException e) {
throw new ReplicationException("Failed to remove last sequence ids, peerId=" + peerId +
", encodedRegionNames.size=" + encodedRegionNames.size(), e);
}
}
@Override
public long getWALPosition(ServerName serverName, String queueId, String fileName)
throws ReplicationException {
byte[] bytes;
try {
bytes = ZKUtil.getData(zookeeper, getFileNode(serverName, queueId, fileName));
} catch (KeeperException | InterruptedException e) {
throw new ReplicationException("Failed to get log position (serverName=" + serverName +
", queueId=" + queueId + ", fileName=" + fileName + ")", e);
}
try {
return ZKUtil.parseWALPositionFrom(bytes);
} catch (DeserializationException de) {
LOG.warn("Failed parse log position (serverName={}, queueId={}, fileName={})",
serverName, queueId, fileName);
}
// if we can not parse the position, start at the beginning of the wal file again
return 0;
}
@Override
public Pair<String, SortedSet<String>> claimQueue(ServerName sourceServerName, String queueId,
ServerName destServerName) throws ReplicationException {
LOG.info("Atomically moving {}/{}'s WALs to {}", sourceServerName, queueId, destServerName);
try {
ZKUtil.createWithParents(zookeeper, getRsNode(destServerName));
} catch (KeeperException e) {
throw new ReplicationException(
"Claim queue queueId=" + queueId + " from " + sourceServerName + " to " + destServerName +
" failed when creating the node for " + destServerName,
e);
}
String newQueueId = queueId + "-" + sourceServerName;
try {
String oldQueueNode = getQueueNode(sourceServerName, queueId);
List<String> wals = ZKUtil.listChildrenNoWatch(zookeeper, oldQueueNode);
if (CollectionUtils.isEmpty(wals)) {
ZKUtil.deleteNodeFailSilent(zookeeper, oldQueueNode);
LOG.info("Removed empty {}/{}", sourceServerName, queueId);
return new Pair<>(newQueueId, Collections.emptySortedSet());
}
String newQueueNode = getQueueNode(destServerName, newQueueId);
List<ZKUtilOp> listOfOps = new ArrayList<>();
SortedSet<String> logQueue = new TreeSet<>();
// create the new cluster znode
listOfOps.add(ZKUtilOp.createAndFailSilent(newQueueNode, HConstants.EMPTY_BYTE_ARRAY));
// get the offset of the logs and set it to new znodes
for (String wal : wals) {
String oldWalNode = getFileNode(oldQueueNode, wal);
byte[] logOffset = ZKUtil.getData(this.zookeeper, oldWalNode);
LOG.debug("Creating {} with data {}", wal, Bytes.toStringBinary(logOffset));
String newWalNode = getFileNode(newQueueNode, wal);
listOfOps.add(ZKUtilOp.createAndFailSilent(newWalNode, logOffset));
listOfOps.add(ZKUtilOp.deleteNodeFailSilent(oldWalNode));
logQueue.add(wal);
}
// add delete op for peer
listOfOps.add(ZKUtilOp.deleteNodeFailSilent(oldQueueNode));
LOG.trace("The multi list size is {}", listOfOps.size());
ZKUtil.multiOrSequential(zookeeper, listOfOps, false);
LOG.info("Atomically moved {}/{}'s WALs to {}", sourceServerName, queueId, destServerName);
return new Pair<>(newQueueId, logQueue);
} catch (NoNodeException | NodeExistsException | NotEmptyException | BadVersionException e) {
// Multi call failed; it looks like some other regionserver took away the logs.
// These exceptions mean that zk tells us the request can not be execute. So return an empty
// queue to tell the upper layer that claim nothing. For other types of exception should be
// thrown out to notify the upper layer.
LOG.info("Claim queue queueId={} from {} to {} failed with {}, someone else took the log?",
queueId,sourceServerName, destServerName, e.toString());
return new Pair<>(newQueueId, Collections.emptySortedSet());
} catch (KeeperException | InterruptedException e) {
throw new ReplicationException("Claim queue queueId=" + queueId + " from " +
sourceServerName + " to " + destServerName + " failed", e);
}
}
@Override
public void removeReplicatorIfQueueIsEmpty(ServerName serverName) throws ReplicationException {
try {
ZKUtil.deleteNodeFailSilent(zookeeper, getRsNode(serverName));
} catch (NotEmptyException e) {
// keep silence to avoid logging too much.
} catch (KeeperException e) {
throw new ReplicationException("Failed to remove replicator for " + serverName, e);
}
}
private List<ServerName> getListOfReplicators0() throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(zookeeper, queuesZNode);
if (children == null) {
children = Collections.emptyList();
}
return children.stream().map(ServerName::parseServerName).collect(toList());
}
@Override
public List<ServerName> getListOfReplicators() throws ReplicationException {
try {
return getListOfReplicators0();
} catch (KeeperException e) {
throw new ReplicationException("Failed to get list of replicators", e);
}
}
private List<String> getWALsInQueue0(ServerName serverName, String queueId)
throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(zookeeper, getQueueNode(serverName,
queueId));
return children != null ? children : Collections.emptyList();
}
@Override
public List<String> getWALsInQueue(ServerName serverName, String queueId)
throws ReplicationException {
try {
return getWALsInQueue0(serverName, queueId);
} catch (KeeperException e) {
throw new ReplicationException(
"Failed to get wals in queue (serverName=" + serverName + ", queueId=" + queueId + ")",
e);
}
}
private List<String> getAllQueues0(ServerName serverName) throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(zookeeper, getRsNode(serverName));
return children != null ? children : Collections.emptyList();
}
@Override
public List<String> getAllQueues(ServerName serverName) throws ReplicationException {
try {
return getAllQueues0(serverName);
} catch (KeeperException e) {
throw new ReplicationException("Failed to get all queues (serverName=" + serverName + ")", e);
}
}
// will be overridden in UTs
@VisibleForTesting
protected int getQueuesZNodeCversion() throws KeeperException {
Stat stat = new Stat();
ZKUtil.getDataNoWatch(this.zookeeper, this.queuesZNode, stat);
return stat.getCversion();
}
@Override
public Set<String> getAllWALs() throws ReplicationException {
try {
for (int retry = 0;; retry++) {
int v0 = getQueuesZNodeCversion();
List<ServerName> rss = getListOfReplicators0();
if (rss.isEmpty()) {
LOG.debug("Didn't find a RegionServer that replicates, won't prevent deletions.");
return Collections.emptySet();
}
Set<String> wals = new HashSet<>();
for (ServerName rs : rss) {
for (String queueId : getAllQueues0(rs)) {
wals.addAll(getWALsInQueue0(rs, queueId));
}
}
int v1 = getQueuesZNodeCversion();
if (v0 == v1) {
return wals;
}
LOG.info("Replication queue node cversion changed from %d to %d, retry = %d",
v0, v1, retry);
}
} catch (KeeperException e) {
throw new ReplicationException("Failed to get all wals", e);
}
}
private String getHFileRefsPeerNode(String peerId) {
return ZNodePaths.joinZNode(hfileRefsZNode, peerId);
}
private String getHFileNode(String peerNode, String fileName) {
return ZNodePaths.joinZNode(peerNode, fileName);
}
@Override
public void addPeerToHFileRefs(String peerId) throws ReplicationException {
String peerNode = getHFileRefsPeerNode(peerId);
try {
if (ZKUtil.checkExists(zookeeper, peerNode) == -1) {
LOG.info("Adding peer {} to hfile reference queue.", peerId);
ZKUtil.createWithParents(zookeeper, peerNode);
}
} catch (KeeperException e) {
throw new ReplicationException("Failed to add peer " + peerId + " to hfile reference queue.",
e);
}
}
@Override
public void removePeerFromHFileRefs(String peerId) throws ReplicationException {
String peerNode = getHFileRefsPeerNode(peerId);
try {
if (ZKUtil.checkExists(zookeeper, peerNode) == -1) {
LOG.debug("Peer {} not found in hfile reference queue.", peerNode);
} else {
LOG.info("Removing peer {} from hfile reference queue.", peerNode);
ZKUtil.deleteNodeRecursively(zookeeper, peerNode);
}
} catch (KeeperException e) {
throw new ReplicationException(
"Failed to remove peer " + peerId + " from hfile reference queue.", e);
}
}
@Override
public void addHFileRefs(String peerId, List<Pair<Path, Path>> pairs)
throws ReplicationException {
String peerNode = getHFileRefsPeerNode(peerId);
LOG.debug("Adding hfile references {} in queue {}", pairs, peerNode);
List<ZKUtilOp> listOfOps = pairs.stream().map(p -> p.getSecond().getName())
.map(n -> getHFileNode(peerNode, n))
.map(f -> ZKUtilOp.createAndFailSilent(f, HConstants.EMPTY_BYTE_ARRAY)).collect(toList());
LOG.debug("The multi list size for adding hfile references in zk for node {} is {}",
peerNode, listOfOps.size());
try {
ZKUtil.multiOrSequential(this.zookeeper, listOfOps, true);
} catch (KeeperException e) {
throw new ReplicationException("Failed to add hfile reference to peer " + peerId, e);
}
}
@Override
public void removeHFileRefs(String peerId, List<String> files) throws ReplicationException {
String peerNode = getHFileRefsPeerNode(peerId);
LOG.debug("Removing hfile references {} from queue {}", files, peerNode);
List<ZKUtilOp> listOfOps = files.stream().map(n -> getHFileNode(peerNode, n))
.map(ZKUtilOp::deleteNodeFailSilent).collect(toList());
LOG.debug("The multi list size for removing hfile references in zk for node {} is {}",
peerNode, listOfOps.size());
try {
ZKUtil.multiOrSequential(this.zookeeper, listOfOps, true);
} catch (KeeperException e) {
throw new ReplicationException("Failed to remove hfile reference from peer " + peerId, e);
}
}
private List<String> getAllPeersFromHFileRefsQueue0() throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(zookeeper, hfileRefsZNode);
return children != null ? children : Collections.emptyList();
}
@Override
public List<String> getAllPeersFromHFileRefsQueue() throws ReplicationException {
try {
return getAllPeersFromHFileRefsQueue0();
} catch (KeeperException e) {
throw new ReplicationException("Failed to get list of all peers in hfile references node.",
e);
}
}
private List<String> getReplicableHFiles0(String peerId) throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(this.zookeeper,
getHFileRefsPeerNode(peerId));
return children != null ? children : Collections.emptyList();
}
@Override
public List<String> getReplicableHFiles(String peerId) throws ReplicationException {
try {
return getReplicableHFiles0(peerId);
} catch (KeeperException e) {
throw new ReplicationException("Failed to get list of hfile references for peer " + peerId,
e);
}
}
// will be overridden in UTs
@VisibleForTesting
protected int getHFileRefsZNodeCversion() throws ReplicationException {
Stat stat = new Stat();
try {
ZKUtil.getDataNoWatch(zookeeper, hfileRefsZNode, stat);
} catch (KeeperException e) {
throw new ReplicationException("Failed to get stat of replication hfile references node.", e);
}
return stat.getCversion();
}
@Override
public Set<String> getAllHFileRefs() throws ReplicationException {
try {
for (int retry = 0;; retry++) {
int v0 = getHFileRefsZNodeCversion();
List<String> peers = getAllPeersFromHFileRefsQueue();
if (peers.isEmpty()) {
LOG.debug("Didn't find any peers with hfile references, won't prevent deletions.");
return Collections.emptySet();
}
Set<String> hfileRefs = new HashSet<>();
for (String peer : peers) {
hfileRefs.addAll(getReplicableHFiles0(peer));
}
int v1 = getHFileRefsZNodeCversion();
if (v0 == v1) {
return hfileRefs;
}
LOG.debug("Replication hfile references node cversion changed from %d to %d, retry = %d",
v0, v1, retry);
}
} catch (KeeperException e) {
throw new ReplicationException("Failed to get all hfile refs", e);
}
}
}
| {
"content_hash": "57ae926ef610eb7ff09ae77b87abe550",
"timestamp": "",
"source": "github",
"line_count": 663,
"max_line_length": 100,
"avg_line_length": 41.29110105580694,
"alnum_prop": 0.6933810637054354,
"repo_name": "ultratendency/hbase",
"id": "38547539227b729fb3834a6f0694e598daf76420",
"size": "28182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hbase-replication/src/main/java/org/apache/hadoop/hbase/replication/ZKReplicationQueueStorage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25330"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "56085"
},
{
"name": "CMake",
"bytes": "13186"
},
{
"name": "CSS",
"bytes": "37063"
},
{
"name": "Dockerfile",
"bytes": "6658"
},
{
"name": "Groovy",
"bytes": "38239"
},
{
"name": "HTML",
"bytes": "17275"
},
{
"name": "Java",
"bytes": "34476127"
},
{
"name": "JavaScript",
"bytes": "2694"
},
{
"name": "Makefile",
"bytes": "1359"
},
{
"name": "PHP",
"bytes": "8385"
},
{
"name": "Perl",
"bytes": "383739"
},
{
"name": "Python",
"bytes": "90220"
},
{
"name": "Ruby",
"bytes": "666059"
},
{
"name": "Shell",
"bytes": "288413"
},
{
"name": "Thrift",
"bytes": "52675"
},
{
"name": "XSLT",
"bytes": "6764"
}
],
"symlink_target": ""
} |
package io.treehopper.enums;
/**
* Hardware PWM frequency
*/
public enum HardwarePwmFrequency {
/**
* 732 Hz PWM frequency
*/
Freq_732Hz(732),
/**
* 183 Hz PWM frequency
*/
Freq_183Hz(183),
/**
* 61 Hz PWM frequency
*/
Freq_61Hz(61);
int frequency;
HardwarePwmFrequency(int frequency) {
this.frequency = frequency;
}
public int getFrequencyHz() {
return frequency;
}
}
| {
"content_hash": "31bc7605b839f18e7e7c587f7d9da880",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 41,
"avg_line_length": 13.823529411764707,
"alnum_prop": 0.5574468085106383,
"repo_name": "treehopper-electronics/treehopper-sdk",
"id": "0fbef4370f83270982179a5d63d35dd32b38d6f9",
"size": "470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/api/treehopper/src/main/java/io/treehopper/enums/HardwarePwmFrequency.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6296"
},
{
"name": "Batchfile",
"bytes": "183"
},
{
"name": "C",
"bytes": "522458"
},
{
"name": "C#",
"bytes": "2112573"
},
{
"name": "C++",
"bytes": "517633"
},
{
"name": "CMake",
"bytes": "4426"
},
{
"name": "Java",
"bytes": "552020"
},
{
"name": "Jupyter Notebook",
"bytes": "169891"
},
{
"name": "Limbo",
"bytes": "19"
},
{
"name": "MATLAB",
"bytes": "1860"
},
{
"name": "Python",
"bytes": "599033"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__negative_strncpy_53d.c
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-53d.tmpl.c
*/
/*
* @description
* CWE: 194 Unexpected Sign Extension
* BadSource: negative Set data to a fixed negative number
* GoodSource: Positive integer
* Sink: strncpy
* BadSink : Copy strings using strncpy() with the length of data
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void CWE194_Unexpected_Sign_Extension__negative_strncpy_53d_badSink(short data)
{
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
strncpy(dest, source, data);
dest[data] = '\0'; /* strncpy() does not always NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE194_Unexpected_Sign_Extension__negative_strncpy_53d_goodG2BSink(short data)
{
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
strncpy(dest, source, data);
dest[data] = '\0'; /* strncpy() does not always NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITGOOD */
| {
"content_hash": "9eb430bdf61e96de58e22503864bea3c",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 156,
"avg_line_length": 32.6875,
"alnum_prop": 0.6123326959847036,
"repo_name": "maurer/tiamat",
"id": "324afa6a56f9db185701994ba7685cab6c76508e",
"size": "2092",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE194_Unexpected_Sign_Extension/s02/CWE194_Unexpected_Sign_Extension__negative_strncpy_53d.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#include "api/audio_codecs/audio_format.h"
#include <utility>
#include "absl/strings/match.h"
namespace webrtc {
SdpAudioFormat::SdpAudioFormat(const SdpAudioFormat&) = default;
SdpAudioFormat::SdpAudioFormat(SdpAudioFormat&&) = default;
SdpAudioFormat::SdpAudioFormat(absl::string_view name,
int clockrate_hz,
size_t num_channels)
: name(name), clockrate_hz(clockrate_hz), num_channels(num_channels) {}
SdpAudioFormat::SdpAudioFormat(absl::string_view name,
int clockrate_hz,
size_t num_channels,
const Parameters& param)
: name(name),
clockrate_hz(clockrate_hz),
num_channels(num_channels),
parameters(param) {}
SdpAudioFormat::SdpAudioFormat(absl::string_view name,
int clockrate_hz,
size_t num_channels,
Parameters&& param)
: name(name),
clockrate_hz(clockrate_hz),
num_channels(num_channels),
parameters(std::move(param)) {}
bool SdpAudioFormat::Matches(const SdpAudioFormat& o) const {
return absl::EqualsIgnoreCase(name, o.name) &&
clockrate_hz == o.clockrate_hz && num_channels == o.num_channels;
}
SdpAudioFormat::~SdpAudioFormat() = default;
SdpAudioFormat& SdpAudioFormat::operator=(const SdpAudioFormat&) = default;
SdpAudioFormat& SdpAudioFormat::operator=(SdpAudioFormat&&) = default;
bool operator==(const SdpAudioFormat& a, const SdpAudioFormat& b) {
return absl::EqualsIgnoreCase(a.name, b.name) &&
a.clockrate_hz == b.clockrate_hz && a.num_channels == b.num_channels &&
a.parameters == b.parameters;
}
AudioCodecInfo::AudioCodecInfo(int sample_rate_hz,
size_t num_channels,
int bitrate_bps)
: AudioCodecInfo(sample_rate_hz,
num_channels,
bitrate_bps,
bitrate_bps,
bitrate_bps) {}
AudioCodecInfo::AudioCodecInfo(int sample_rate_hz,
size_t num_channels,
int default_bitrate_bps,
int min_bitrate_bps,
int max_bitrate_bps)
: sample_rate_hz(sample_rate_hz),
num_channels(num_channels),
default_bitrate_bps(default_bitrate_bps),
min_bitrate_bps(min_bitrate_bps),
max_bitrate_bps(max_bitrate_bps) {
RTC_DCHECK_GT(sample_rate_hz, 0);
RTC_DCHECK_GT(num_channels, 0);
RTC_DCHECK_GE(min_bitrate_bps, 0);
RTC_DCHECK_LE(min_bitrate_bps, default_bitrate_bps);
RTC_DCHECK_GE(max_bitrate_bps, default_bitrate_bps);
}
} // namespace webrtc
| {
"content_hash": "d53f603f5c9274a821fe518bdc3a0003",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 80,
"avg_line_length": 35.84615384615385,
"alnum_prop": 0.5861945636623748,
"repo_name": "endlessm/chromium-browser",
"id": "2a529a49ee5b5a87def17f1ffd7481d2340511da",
"size": "3208",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "third_party/webrtc/api/audio_codecs/audio_format.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "dd9080a12d1807a155be2ee2dfa47c05",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "b474d9cb6c84c4a0cb453821301bcd6e4f2f587c",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Gomphrena/Gomphrena purpurea/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('autoemails', '0016_auto_20210809_0701'),
]
operations = [
migrations.AddField(
model_name='rqjob',
name='action_name',
field=models.CharField(blank=True, default='', help_text='Action class that will be executed.', max_length=100, verbose_name='Action Class'),
),
migrations.AddField(
model_name='rqjob',
name='interval',
field=models.IntegerField(blank=True, null=True, verbose_name='Interval in seconds'),
),
migrations.AddField(
model_name='rqjob',
name='result_ttl',
field=models.IntegerField(blank=True, null=True, verbose_name='Result TTL'),
),
migrations.AlterField(
model_name='trigger',
name='action',
field=models.CharField(choices=[('new-instructor', 'Instructor is added to the workshop'), ('new-supporting-instructor', 'Supporting Instructor is added to the workshop'), ('week-after-workshop-completion', '7 days past the end date of an active workshop'), ('self-organised-request-form', 'A new event is created from Self-Organised Request Form'), ('instructors-host-introduction', 'Introduction of instrutors and host (centr. org. workshop)'), ('ask-for-website', 'Website URL is missing'), ('recruit-helpers', 'Recruit helpers'), ('workshop-request-response1', 'Response to Workshop Request 1'), ('workshop-request-response2', 'Response to Workshop Request 2'), ('workshop-request-response3', 'Response to Workshop Request 3'), ('consent-required', 'There is a new or updated term added that the users should consent to'), ('profile-update', 'Reminder to for the user to update the information in their profile.')], max_length=50, verbose_name='Action'),
),
]
| {
"content_hash": "b583702c88a015c4cf5ac567a60efbe8",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 970,
"avg_line_length": 61.61290322580645,
"alnum_prop": 0.6565445026178011,
"repo_name": "pbanaszkiewicz/amy",
"id": "8a8bae01c8692cf0b70bdca5ca06188b6f6b8af8",
"size": "1960",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "amy/autoemails/migrations/0017_auto_20210901_0226.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5850"
},
{
"name": "Dockerfile",
"bytes": "1034"
},
{
"name": "HTML",
"bytes": "313293"
},
{
"name": "JavaScript",
"bytes": "39427"
},
{
"name": "Makefile",
"bytes": "1780"
},
{
"name": "Python",
"bytes": "2707815"
}
],
"symlink_target": ""
} |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//
// Module dependencies.
var fs = require('fs');
var qs = require('querystring');
var url = require('url');
var util = require('util');
var mime = require('mime');
var _ = require('underscore');
var crypto = require('crypto');
var extend = require('extend');
var azureCommon = require('./../../common/common');
var BlockRangeStream = require('./internal/blockrangestream');
var PageRangeStream = require('./internal/pagerangestream');
var RangeStream = require('./../../common/streams/rangestream');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var validate = azureCommon.validate;
var StorageServiceClient = azureCommon.StorageServiceClient;
var WebResource = azureCommon.WebResource;
// Constants
var Constants = azureCommon.Constants;
var BlobConstants = Constants.BlobConstants;
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var RequestLocationMode = Constants.RequestLocationMode;
// Streams
var BatchOperation = azureCommon.BatchOperation;
var SpeedSummary = azureCommon.SpeedSummary;
var ChunkAllocator = azureCommon.ChunkAllocator;
var ChunkStream = azureCommon.ChunkStream;
var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream;
var FileReadStream = azureCommon.FileReadStream;
// Models requires
var AclResult = azureCommon.AclResult;
var ServiceStatsParser = azureCommon.ServiceStatsParser;
var BlockListResult = require('./models/blocklistresult');
var BlobResult = require('./models/blobresult');
var ContainerResult = require('./models/containerresult');
var LeaseResult = require('./models/leaseresult');
var BlobUtilities = require('./blobutilities');
/**
* Creates a new BlobService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The BlobService class is used to perform operations on the Microsoft Azure Blob Service.
* The Blob Service provides storage for binary large objects, and provides
* functions for working with data stored in blobs as either streams or pages of data.
*
* For more information on the Blob Service, as well as task focused information on using it in a Node.js application, see
* [How to Use the Blob Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/).
* The following defaults can be set on the blob service.
* singleBlobPutThresholdInBytes The default maximum size, in bytes, of a blob before it must be separated into blocks.
* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Blob service.
* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Blob service.
* defaultLocationMode The default location mode for requests made via the Blob service.
* parallelOperationThreadCount The number of parallel operations that may be performed when uploading a blob that is greater than
* the value specified by the singleBlobPutThresholdInBytes property in size.
* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Blob service; true to use the
* Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString] The storage account or the connection string.
* @param {string} [storageAccessKey] The storage access key.
* @param {string|object} [host] The host address. To define primary only, pass a string.
* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken] The Shared Access Signature token.
*/
function BlobService(storageAccountOrConnectionString, storageAccessKey, host, sasToken) {
var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken);
BlobService['super_'].call(this,
storageServiceSettings._name,
storageServiceSettings._key,
storageServiceSettings._blobEndpoint,
storageServiceSettings._usePathStyleUri,
storageServiceSettings._sasToken);
this.singleBlobPutThresholdInBytes = BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES;
this.parallelOperationThreadCount = Constants.DEFAULT_PARALLEL_OPERATION_THREAD_COUNT;
}
util.inherits(BlobService, StorageServiceClient);
// Non-class methods
/**
* Create resource name
* @ignore
*
* @param {string} containerName Container name
* @param {string} blobName Blob name
* @return {string} The encoded resource name.
*/
function createResourceName(containerName, blobName, forSAS) {
// Resource name
if (blobName && !forSAS) {
blobName = encodeURIComponent(blobName);
blobName = blobName.replace(/%2F/g, '/');
blobName = blobName.replace(/%5C/g, '/');
blobName = blobName.replace(/\+/g, '%20');
}
// return URI encoded resource name
if (blobName) {
return containerName + '/' + blobName;
}
else {
return containerName;
}
}
// Blob service methods
/**
* Gets the service stats for a storage account’s Blob service.
*
* @this {BlobService}
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the stats and
* `response` will contain information related to this operation.
*/
BlobService.prototype.getServiceStats = function (optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
validate.validateArgs('getServiceStats', function (v) {
v.callback(callback);
});
var webResource = WebResource.get()
.withQueryOption(QueryStringConstants.COMP, 'stats')
.withQueryOption(QueryStringConstants.RESTYPE, 'service');
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
var processResponseCallback = function (responseObject, next) {
responseObject.serviceStatsResult = null;
if (!responseObject.error) {
responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
}
// function to be called after all filters
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
};
// call the first filter
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Gets the properties of a storage account’s Blob service, including Azure Storage Analytics.
*
* @this {BlobService}
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the properties
* and `response` will contain information related to this operation.
*/
BlobService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
return this.getAccountServiceProperties(optionsOrCallback, callback);
};
/**
* Sets the properties of a storage account’s Blob service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {BlobService}
* @param {object} serviceProperties The service properties.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise, `response`
* will contain information related to this operation.
*/
BlobService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of container items under the specified account.
*
* @this {BlobService}
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage.
* @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of containers and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listContainersSegmented = function (currentToken, optionsOrCallback, callback) {
this.listContainersSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of container items whose names begin with the specified prefix under the specified account.
*
* @this {BlobService}
* @param {string} prefix The prefix of the container name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {string} [options.prefix] Filters the results to return only containers whose name begins with the specified prefix.
* @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage.
* @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of containers and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listContainersSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listContainers', function (v) {
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.get()
.withQueryOption(QueryStringConstants.COMP, 'list')
.withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
.withQueryOption(QueryStringConstants.INCLUDE, options.include);
if (!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
}
webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.listContainersResult = null;
if (!responseObject.error) {
responseObject.listContainersResult = {
entries: null,
continuationToken: null
};
responseObject.listContainersResult.entries = [];
var containers = [];
if (responseObject.response.body.EnumerationResults.Containers && responseObject.response.body.EnumerationResults.Containers.Container) {
containers = responseObject.response.body.EnumerationResults.Containers.Container;
if (!_.isArray(containers)) {
containers = [ containers ];
}
}
containers.forEach(function (currentContainer) {
var containerResult = ContainerResult.parse(currentContainer);
responseObject.listContainersResult.entries.push(containerResult);
});
if (responseObject.response.body.EnumerationResults.NextMarker) {
responseObject.listContainersResult.continuationToken = {
nextMarker: null,
targetLocation: null
};
responseObject.listContainersResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
responseObject.listContainersResult.continuationToken.targetLocation = responseObject.targetLocation;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.listContainersResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
// Container methods
/**
* Checks whether or not a container exists on the service.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will
* be true if the container exists, or false if the container does not exist.
* `response` will contain information related to this operation.
*/
BlobService.prototype.doesContainerExist = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('doesContainerExist', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
this._doesContainerExist(container, false, options, callback);
};
/**
* Creates a new container under the specified account.
* If a container with the same name already exists, the operation fails.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the container information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.createContainer = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createContainer', function (v) {
v.string(container, 'container');
v.test(function () { return container !== '$logs'; },
'Container name format is incorrect');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.put(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container');
webResource.addOptionalMetadataHeaders(options.metadata);
webResource.withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel);
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
if (options.metadata) {
responseObject.containerResult.metadata = options.metadata;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Creates a new container under the specified account if the container does not exists.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will
* be true if the container was created, or false if the container
* already exists.
* `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error) {
* if(!error) {
* // Container created or exists, and is public
* }
* });
*/
BlobService.prototype.createContainerIfNotExists = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createContainerIfNotExists', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesContainerExist(container, true, options, function (error, exists, response) {
if (error) {
callback(error, exists, response);
} else if (exists) {
response.isSuccessful = true;
callback(error, false, response);
} else {
self.createContainer(container, options, function (createError, responseContainer, createResponse) {
var created;
if (!createError) {
created = true;
}
else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS) {
// If it was created before, there was no actual error.
createError = null;
created = false;
createResponse.isSuccessful = true;
}
callback(createError, created, createResponse);
});
}
});
};
/**
* Retrieves a container and its properties from a specified account.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {string} [options.leaseId] The container lease identifier.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information for the container.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerProperties = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getContainerProperties', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.head(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Returns all user-defined metadata for the container.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information for the container.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerMetadata = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getContainerMetadata', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.head(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withQueryOption(QueryStringConstants.COMP, 'metadata')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Sets the container's metadata.
*
* Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container.
* It's not possible to modify an individual name/value pair.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} metadata The metadata key/value pairs.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {object} [options.accessConditions] See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.setContainerMetadata = function (container, metadata, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setContainerMetadata', function (v) {
v.string(container, 'container');
v.object(metadata, 'metadata');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.put(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withQueryOption(QueryStringConstants.COMP, 'metadata')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
webResource.addOptionalMetadataHeaders(metadata);
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Gets the container's ACL.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information for the container.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerAcl = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getContainerAcl', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.get(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withQueryOption(QueryStringConstants.COMP, 'acl')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
responseObject.containerResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Updates the container's ACL.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array.
* @param {object} [options] The request options.
* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access.
* @param {string} [options.leaseId] The container lease identifier.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information for the container.
* `response` will contain information related to this operation.
*/
BlobService.prototype.setContainerAcl = function (container, signedIdentifiers, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setContainerAcl', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var policies = null;
if (signedIdentifiers) {
if (!_.isArray(signedIdentifiers)) {
throw new Error(SR.INVALID_SIGNED_IDENTIFIERS);
}
policies = AclResult.serialize(signedIdentifiers);
}
var webResource = WebResource.put(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withQueryOption(QueryStringConstants.COMP, 'acl')
.withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
.withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel)
.withHeader(HeaderConstants.LEASE_ID, options.leaseId)
.withBody(policies);
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container, options.publicAccessLevel);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
if (signedIdentifiers) {
responseObject.containerResult.signedIdentifiers = signedIdentifiers;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Marks the specified container for deletion.
* The container and any blobs contained within it are later deleted during garbage collection.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.deleteContainer = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteContainer', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.del(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Marks the specified container for deletion if it exists.
* The container and any blobs contained within it are later deleted during garbage collection.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will
* be true if the container exists and was deleted, or false if the container
* did not exist.
* `response` will contain information related to this operation.
*/
BlobService.prototype.deleteContainerIfExists = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteContainerIfExists', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesContainerExist(container, true, options, function (error, exists, response) {
if (error) {
callback(error, exists, response);
} else if (!exists) {
response.isSuccessful = true;
callback(error, false, response);
} else {
self.deleteContainer(container, options, function (deleteError, deleteResponse) {
var deleted;
if (!deleteError) {
deleted = true;
} else if (deleteError && deleteError.statuscode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.BlobErrorCodeStrings.CONTAINER_NOT_FOUND) {
// If it was deleted already, there was no actual error.
deleted = false;
deleteError = null;
deleteResponse.isSuccessful = true;
}
callback(deleteError, deleted, deleteResponse);
});
}
});
};
/**
* Lists a segment containing a collection of blob directory items in the container.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {int} [options.maxResults] Specifies the maximum number of directories to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of directories and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobDirectoriesSegmented = function (container, currentToken, optionsOrCallback, callback) {
this.listBlobDirectoriesSegmentedWithPrefix(container, null /* prefix */, currentToken, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of blob directory items in the container.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} prefix The prefix of the blob directory.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {int} [options.maxResults] Specifies the maximum number of directories to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of directories and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobDirectoriesSegmentedWithPrefix = function (container, prefix, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
userOptions.delimiter = '/';
this._listBlobsOrDircotriesSegmentedWithPrefix(container, prefix, currentToken, BlobConstants.ListBlobTypes.Directory, userOptions, callback);
};
/**
* Lists a segment containing a collection of blob items in the container.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {string} [options.delimiter] Delimiter, i.e. '/', for specifying folder hierarchy.
* @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs'). Multiple values can be added separated with a comma (,)
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of blobs and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobsSegmented = function (container, currentToken, optionsOrCallback, callback) {
this.listBlobsSegmentedWithPrefix(container, null /* prefix */, currentToken, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} prefix The prefix of the blob name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {string} [options.delimiter] Delimiter, i.e. '/', for specifying folder hierarchy.
* @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs'). Multiple values can be added separated with a comma (,)
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs]The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the entries of blobs and the continuation token for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobsSegmentedWithPrefix = function (container, prefix, currentToken, optionsOrCallback, callback) {
this._listBlobsOrDircotriesSegmentedWithPrefix(container, prefix, currentToken, BlobConstants.ListBlobTypes.Blob, optionsOrCallback, callback);
};
// Lease methods
/**
* Acquires a new lease. If container and blob are specified, acquires a blob lease. Otherwise, if only container is specified and blob is null, acquires a container lease.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.leaseDuration] The lease duration in seconds. A non-infinite lease can be between 15 and 60 seconds. Default is never to expire.
* @param {string} [options.proposedLeaseId] The proposed lease identifier. Must be a GUID.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the lease information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.acquireLease = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('acquireLease', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
if (!options.leaseDuration) {
options.leaseDuration = -1;
}
this._leaseImpl(container, blob, null /* leaseId */, BlobConstants.LeaseOperation.ACQUIRE, options, callback);
};
/**
* Renews an existing lease. If container and blob are specified, renews the blob lease. Otherwise, if only container is specified and blob is null, renews the container lease.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} leaseId The lease identifier. Must be a GUID.
* @param {object} [options] The request options.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the lease information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.renewLease = function (container, blob, leaseId, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('renewLease', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.RENEW, options, callback);
};
/**
* Changes the lease ID of an active lease. If container and blob are specified, changes the blob lease. Otherwise, if only container is specified and blob is null, changes the
* container lease.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} leaseId The current lease identifier.
* @param {string} proposedLeaseId The proposed lease identifier. Must be a GUID.
* @param {object} [options] The request options.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the lease information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.changeLease = function (container, blob, leaseId, proposedLeaseId, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('changeLease', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.proposedLeaseId = proposedLeaseId;
this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.CHANGE, options, callback);
};
/**
* Releases the lease. If container and blob are specified, releases the blob lease. Otherwise, if only container is specified and blob is null, releases the container lease.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} leaseId The lease identifier.
* @param {object} [options] The request options.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the lease information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.releaseLease = function (container, blob, leaseId, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('releaseLease', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.RELEASE, options, callback);
};
/**
* Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. If container and blob are specified, breaks the blob lease.
* Otherwise, if only container is specified and blob is null, breaks the container lease.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {int} [options.leaseBreakPeriod] The lease break period, between 0 and 60 seconds. If unspecified, a fixed-duration lease breaks after
* the remaining lease period elapses, and an infinite lease breaks immediately.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the lease information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.breakLease = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('breakLease', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
this._leaseImpl(container, blob, null /*leaseId*/, BlobConstants.LeaseOperation.BREAK, options, callback);
};
// Blob methods
/**
* Returns all user-defined metadata, standard HTTP properties, and system properties for the blob.
* It does not return or modify the content of the blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getBlobProperties = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getBlobProperties', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.head(resourceName);
if (options.snapshotId) {
webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
}
BlobResult.setHeadersFromBlob(webResource, options);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Returns all user-defined metadata for the specified blob or snapshot.
* It does not modify or return the content of the blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getBlobMetadata = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getBlobMetadata', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.head(resourceName);
webResource.withQueryOption(QueryStringConstants.COMP, 'metadata');
webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
BlobResult.setHeadersFromBlob(webResource, options);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Sets user-defined properties for the specified blob or snapshot.
* It does not modify or return the content of the blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [properties] The blob properties to set.
* @param {string} [properties.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [properties.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [properties.contentLanguage] The natural languages used by this resource.
* @param {string} [properties.contentMD5] The MD5 hash of the blob content.
* @param {string} [properties.cacheControl] The blob's cache control.
* @param {string} [properties.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
*/
BlobService.prototype.setBlobProperties = function (container, blob, properties, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setBlobProperties', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, properties, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'properties');
BlobResult.setPropertiesFromBlob(webResource, options);
this._setBlobPropertiesHelper({
webResource: webResource,
options: options,
container: container,
blob: blob,
callback: callback
});
};
/**
* Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs
* It does not modify or return the content of the blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} metadata The metadata key/value pairs.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information on the blob.
* `response` will contain information related to this operation.
*/
BlobService.prototype.setBlobMetadata = function (container, blob, metadata, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setBlobMetadata', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.object(metadata, 'metadata');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'metadata');
webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
options.metadata = metadata;
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Downloads a blob into a file.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} localFileName The local path to the file to be downloaded.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The upload tracker objects.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the blob information.
* `response` will contain information related to this operation.
* @return {SpeedSummary}
*
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.getBlobToLocalFile('taskcontainer', 'task1', 'task1-download.txt', function(error, serverBlob) {
* if(!error) {
* // Blob available in serverBlob.blob variable
* }
*/
BlobService.prototype.getBlobToLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
validate.validateArgs('getBlobToLocalFile', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.string(localFileName, 'localFileName');
v.containerNameIsValid(container);
v.callback(callback);
});
return this._getBlobToLocalFile(container, blob, localFileName, options, callback);
};
/**
* Provides a stream to read from a blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the blob information.
* `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var writable = fs.createWriteStream(destinationFileNameTarget);
* blobService.createReadStream(containerName, blobName).pipe(writable);
*/
BlobService.prototype.createReadStream = function (container, blob, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
validate.validateArgs('createReadStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
});
var readStream = new ChunkStream();
this.getBlobToStream(container, blob, readStream, options, function (error, responseBlob, response) {
if (error) {
readStream.emit('error', error);
}
if (callback) {
callback(error, responseBlob, response);
}
});
return readStream;
};
/**
* Downloads a blob into a stream.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} writeStream The write stream.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the blob information.
* `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.getBlobToStream('taskcontainer', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverBlob) {
* if(!error) {
* // Blob available in serverBlob.blob variable
* }
* });
*/
BlobService.prototype.getBlobToStream = function (container, blob, writeStream, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getBlobToStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.object(writeStream, 'writeStream');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var propertiesRequestOptions = {
timeoutIntervalInMs : options.timeoutIntervalInMs,
snapshotId : options.snapshotId,
accessConditions : options.accessConditions
};
var self = this;
this.getBlobProperties(container, blob, propertiesRequestOptions, function (error, properties) {
if (error) {
callback(error);
} else {
var size;
if (options.rangeStart) {
var endOffset = properties.contentLength - 1;
var end = options.rangeEnd ? Math.min(options.rangeEnd, endOffset) : endOffset;
size = end - options.rangeStart + 1;
} else {
size = properties.contentLength;
}
if (size > self.singleBlobPutThresholdInBytes) {
options.contentMD5 = properties.contentMD5;
self._getBlobToRangeStream(container, blob, properties.blobType, writeStream, options, callback);
} else {
self._getBlobToStream(container, blob, writeStream, options, callback);
}
}
});
return options.speedSummary;
};
/**
* Downloads a blob into a text string.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {BlobService~blobToText} callback `error` will contain information
* if an error occurs; otherwise `text` will contain the blob contents,
* and `blockBlob` will contain
* the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getBlobToText = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getBlobToText', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.get(resourceName)
.withRawResponse();
webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
BlobResult.setHeadersFromBlob(webResource, options);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.text = null;
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
responseObject.text = responseObject.response.body;
self._validateLengthAndMD5(options, responseObject);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.text, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection.
* If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots,
* or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error
* and nothing will be deleted.
* If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; `response` will contain information related to this operation.
*/
BlobService.prototype.deleteBlob = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteBlob', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.del(resourceName)
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
if (!azureutil.objectIsNull(options.snapshotId) && !azureutil.objectIsNull(options.deleteSnapshots)) {
throw new Error(SR.INVALID_DELETE_SNAPSHOT_OPTION);
}
webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
webResource.withHeader(HeaderConstants.DELETE_SNAPSHOT, options.deleteSnapshots);
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Checks whether or not a blob exists on the service.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `errorOrResult` will
* be true if the blob exists, or false if the blob does not exist.
* `response` will contain information related to this operation.
*/
BlobService.prototype.doesBlobExist = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('doesBlobExist', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
this._doesBlobExist(container, blob, false, options, callback);
};
/**
* Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted during garbage collection.
* If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots,
* or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error
* and nothing will be deleted.
* If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will
* be true if the blob was deleted, or false if the blob
* does not exist.
* `response` will contain information related to this operation.
*/
BlobService.prototype.deleteBlobIfExists = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteBlobIfExists', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesBlobExist(container, blob, true, options, function (error, exists, response) {
if (error) {
callback(error, exists, response);
} else if (!exists) {
response.isSuccessful = true;
callback(error, false, response);
} else {
self.deleteBlob(container, blob, options, function (deleteError, deleteResponse) {
var deleted;
if (!deleteError) {
deleted = true;
} else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.BlobErrorCodeStrings.BLOB_NOT_FOUND) {
// If it was deleted already, there was no actual error.
deleted = false;
deleteError = null;
deleteResponse.isSuccessful = true;
}
callback(deleteError, deleted, deleteResponse);
});
}
});
};
/**
* Creates a read-only snapshot of a blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the ID of the snapshot.
* `response` will contain information related to this operation.
*/
BlobService.prototype.createBlobSnapshot = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createBlobSnapshot', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'snapshot');
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
responseObject.snapshotId = null;
if (!responseObject.error) {
responseObject.snapshotId = responseObject.response.headers[HeaderConstants.SNAPSHOT];
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.snapshotId, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob.
*
* @this {BlobService}
* @param {string} sourceUri The source blob URI.
* @param {string} targetContainer The target container name.
* @param {string} targetBlob The target blob name.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The source blob snapshot identifier.
* @param {object} [options.metadata] The target blob metadata key/value pairs.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.sourceLeaseId] The source blob lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {object} [options.sourceAccessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.startCopyBlob = function (sourceUri, targetContainer, targetBlob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('startCopyBlob', function (v) {
v.string(sourceUri, 'sourceUri');
v.string(targetContainer, 'targetContainer');
v.string(targetBlob, 'targetBlob');
v.containerNameIsValid(targetContainer);
v.callback(callback);
});
var targetResourceName = createResourceName(targetContainer, targetBlob);
var options = extend(true, {}, userOptions);
if (options.snapshotId) {
sourceUri += '?snapshot=' + options.snapshotId;
}
var webResource = WebResource.put(targetResourceName)
.withHeader(HeaderConstants.COPY_SOURCE, sourceUri);
webResource.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
webResource.withHeader(HeaderConstants.SOURCE_LEASE_ID, options.sourceLeaseId);
webResource.addOptionalMetadataHeaders(options.metadata);
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(targetContainer, targetBlob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
if (options.metadata) {
responseObject.blobResult.metadata = options.metadata;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Abort a blob copy operation.
*
* @this {BlobService}
* @param {string} container The destination container name.
* @param {string} blob The destination blob name.
* @param {string} copyId The copy operation identifier.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.abortCopyBlob = function (container, blob, copyId, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('abortCopyBlob', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var resourceName = createResourceName(container, blob);
var options = extend(true, {}, userOptions);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COPY_ID, copyId)
.withQueryOption(QueryStringConstants.COMP, 'copy')
.withHeader(HeaderConstants.COPY_ACTION, 'abort');
webResource.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Retrieves a shared access signature token.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} [blob] The blob name.
* @param {object} sharedAccessPolicy The shared access policy.
* @param {string} [sharedAccessPolicy.Id] The signed identifier.
* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type.
* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {object} [headers] The optional header values to set for a blob returned wth this SAS.
* @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used.
* @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used.
* @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used.
* @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used.
* @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used.
* @return {string} The shared access signature query string. Note this string does not contain the leading "?".
*/
BlobService.prototype.generateSharedAccessSignature = function (container, blob, sharedAccessPolicy, headers) {
// check if the BlobService is able to generate a shared access signature
if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) {
throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
}
// Validate container name. Blob name is optional.
validate.validateArgs('generateSharedAccessSignature', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.object(sharedAccessPolicy, 'sharedAccessPolicy');
});
var resourceType = BlobConstants.ResourceTypes.CONTAINER;
if (blob) {
validate.validateArgs('generateSharedAccessSignature', function (v) {
v.string(blob, 'blob');
});
resourceType = BlobConstants.ResourceTypes.BLOB;
}
if (sharedAccessPolicy.AccessPolicy) {
if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Start)) {
if (!_.isDate(sharedAccessPolicy.AccessPolicy.Start)) {
sharedAccessPolicy.AccessPolicy.Start = new Date(sharedAccessPolicy.AccessPolicy.Start);
}
sharedAccessPolicy.AccessPolicy.Start = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Start);
}
if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Expiry)) {
if (!_.isDate(sharedAccessPolicy.AccessPolicy.Expiry)) {
sharedAccessPolicy.AccessPolicy.Expiry = new Date(sharedAccessPolicy.AccessPolicy.Expiry);
}
sharedAccessPolicy.AccessPolicy.Expiry = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Expiry);
}
}
var resourceName = createResourceName(container, blob, true);
return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Blob, resourceName, sharedAccessPolicy, null, { headers: headers, resourceType: resourceType });
};
/**
* Retrieves a blob or container URL.
*
* @param {string} container The container name.
* @param {string} [blob] The blob name.
* @param {string} [sasToken] The Shared Access Signature token.
* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint.
* @return {string} The formatted URL string.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* //create a SAS that expires in an hour
* var sasToken = blobService.generateSharedAccessSignature(containerName, blobName, { AccessPolicy: { Expiry: azure.date.minutesFromNow(60); } });
* var sasUrl = blobService.getUrl(containerName, blobName, sasToken, true);
*/
BlobService.prototype.getUrl = function (container, blob, sasToken, primary) {
validate.validateArgs('getUrl', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
});
var host;
if (!azureutil.objectIsNull(primary) && primary === false) {
host = this.host.secondaryHost;
}
else {
host = this.host.primaryHost;
}
host = azureutil.trimPortFromUri(host);
return url.resolve(host, url.format({ pathname: this._getPath('/' + createResourceName(container, blob)), query: qs.parse(sasToken) }));
};
// Page blob methods
/**
* Creates a page blob of the specified length. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {int} length The length of the page blob in bytes.
* @param {object} [options] The request options.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {string} [options.sequenceNumber] The blob's sequence number. (x-ms-blob-sequence-number)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.createPageBlob = function (container, blob, length, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createPageBlob', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.value(length, 'length');
v.callback(callback);
});
if (length && length % BlobConstants.PAGE_SIZE !== 0) {
throw new Error(SR.INVALID_PAGE_BLOB_LENGTH);
}
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.PAGE)
.withHeader(HeaderConstants.BLOB_CONTENT_LENGTH, length)
.withHeader(HeaderConstants.CONTENT_LENGTH, 0)
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Uploads a page blob from file. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param (string) localFileName The local path to the file to be uploaded.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The upload tracker objects.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.createPageBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.PAGE, localFileName, optionsOrCallback, callback);
};
/**
* Uploads a page blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The download tracker objects;
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.createPageBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.PAGE, stream, streamLength, optionsOrCallback, callback);
};
/**
* Provides a stream to write to a page blob. Assumes that the blob exists.
* If it does not, please create the blob using createPageBlob before calling this method or use createWriteStreamNewPageBlob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs and true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createPageBlob(containerName, blobName, 1024, function (err) {
* // Pipe file to a blob
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToExistingPageBlob(containerName, blobName));
* });
*/
BlobService.prototype.createWriteStreamToExistingPageBlob = function (container, blob, optionsOrCallback, callback) {
return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.PAGE, 0, false, optionsOrCallback, callback);
};
/**
* Provides a stream to write to a page blob. Creates the blob before writing data. If the blob already exists on the service, it will be overwritten.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} length The blob length.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs and true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createPageBlob(containerName, blobName, 1024, function (err) {
* // Pipe file to a blob
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToNewPageBlob(containerName, blobName));
* });
*/
BlobService.prototype.createWriteStreamToNewPageBlob = function (container, blob, length, optionsOrCallback, callback) {
return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.PAGE, length, true, optionsOrCallback, callback);
};
/**
* Updates a page blob from a stream.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} readStream The read stream.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentMD5] An optional hash value used to ensure transactional integrity for the page.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.createPagesFromStream = function (container, blob, readStream, rangeStart, rangeEnd, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createPagesFromStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
if ((rangeEnd - rangeStart) + 1 > BlobConstants.MAX_UPDATE_PAGE_SIZE) {
throw new Error(SR.INVALID_PAGE_RANGE_FOR_UPDATE);
}
var self = this;
if (azureutil.objectIsNull(options.contentMD5) && options.useTransactionalMD5) {
azureutil.calculateMD5(readStream, BlobConstants.MAX_UPDATE_PAGE_SIZE, options, function (internalBuff) {
self._createPages(container, blob, internalBuff, null /* stream */, rangeStart, rangeEnd, options, callback);
});
} else {
self._createPages(container, blob, null /* text */, readStream, rangeStart, rangeEnd, options, callback);
}
};
/**
* Lists page ranges. Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {int} [options.rangeStart] The range start.
* @param {int} [options.rangeEnd] The range end.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the page range information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listPageRanges = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listPageRanges', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.get(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'pagelist')
.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
if (options.rangeStart && options.rangeStart % BlobConstants.PAGE_SIZE !== 0) {
throw new Error(SR.INVALID_PAGE_START_OFFSET);
}
if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) {
throw new Error(SR.INVALID_PAGE_END_OFFSET);
}
BlobResult.setHeadersFromBlob(webResource, options);
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
var processResponseCallback = function (responseObject, next) {
responseObject.pageRanges = null;
if (!responseObject.error) {
responseObject.pageRanges = [];
var pageRanges = [];
if (responseObject.response.body.PageList.PageRange) {
pageRanges = responseObject.response.body.PageList.PageRange;
if (!_.isArray(pageRanges)) {
pageRanges = [ pageRanges ];
}
}
pageRanges.forEach(function (pageRange) {
var range = {
start: parseInt(pageRange.Start, 10),
end: parseInt(pageRange.End, 10)
};
responseObject.pageRanges.push(range);
});
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.pageRanges, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Clears a range of pages.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.clearPageRange = function (container, blob, rangeStart, rangeEnd, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('clearPageRange', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var request = this._updatePageBlobPagesImpl(container, blob, rangeStart, rangeEnd, BlobConstants.PageWriteOptions.CLEAR, options);
var self = this;
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
self.performRequest(request, null, options, processResponseCallback);
};
/**
* Resizes a page blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {String} size The size of the page blob, in bytes.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The blob lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
*/
BlobService.prototype.resizePageBlob = function (container, blob, size, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('resizePageBlob', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'properties');
if (size && size % BlobConstants.PAGE_SIZE !== 0) {
throw new Error(SR.INVALID_PAGE_BLOB_LENGTH);
}
webResource.withHeader(HeaderConstants.BLOB_CONTENT_LENGTH, size);
this._setBlobPropertiesHelper({
webResource: webResource,
options: options,
container: container,
blob: blob,
callback: callback
});
};
/**
* Sets the page blob's sequence number.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {SequenceNumberAction} sequenceNumberAction A value indicating the operation to perform on the sequence number.
* The allowed values are defined in azure.BlobUtilities.SequenceNumberAction.
* @param {string} sequenceNumber The sequence number. The value of the sequence number must be between 0 and 2^63 - 1.
* Set this parameter to null if this operation is an increment action.
* @param {object} [options] The request options.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
*/
BlobService.prototype.setPageBlobSequenceNumber = function (container, blob, sequenceNumberAction, sequenceNumber, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setPageBlobSequenceNumber', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
if (sequenceNumberAction === BlobUtilities.SequenceNumberAction.INCREMENT) {
if (!azureutil.objectIsNull(sequenceNumber)) {
throw new Error(SR.BLOB_INVALID_SEQUENCE_NUMBER);
}
} else {
if (azureutil.objectIsNull(sequenceNumber)) {
throw new Error(util.format(SR.ARGUMENT_NULL_OR_EMPTY, 'sequenceNumber'));
}
}
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'properties')
.withHeader(HeaderConstants.SEQUENCE_NUMBER_ACTION, sequenceNumberAction);
if (sequenceNumberAction !== BlobUtilities.SequenceNumberAction.INCREMENT) {
webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER, sequenceNumber);
}
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
// Block blob methods
/**
* Creates a new block blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} localFileName The local path to the file to be uploaded.
* @param {object} [options] The request options.
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.createBlockBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.BLOCK, localFileName, optionsOrCallback, callback);
};
/**
* Uploads a block blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The download tracker objects.
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.createBlockBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.BLOCK, stream, streamLength, optionsOrCallback, callback);
};
/**
* Uploads a block blob from a text string. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|object} text The blob text, as a string or in a Buffer.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
* @return {undefined}
*/
BlobService.prototype.createBlockBlobFromText = function (container, blob, text, optionsOrCallback, callback) {
return this._createBlobFromText(container, blob, BlobConstants.BlobTypes.BLOCK, text, optionsOrCallback, callback);
};
/**
* Provides a stream to write to a block blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs and true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.position] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToBlockBlob(containerName, blobName, { blockIdPrefix: 'block' }));
*/
BlobService.prototype.createWriteStreamToBlockBlob = function (container, blob, optionsOrCallback, callback) {
return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.BLOCK, 0, false, optionsOrCallback, callback);
};
/**
* Creates a new block to be committed as part of a blob.
*
* @this {BlobService}
* @param {string} blockId The block identifier.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} readStream The read stream.
* @param {int} streamLength The stream length.
* @param {object} [options] The request options.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentMD5] The blob’s MD5 hash.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.createBlockFromStream = function (blockId, container, blob, readStream, streamLength, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createBlockFromStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.exists(readStream, 'readStream');
v.value(streamLength, 'streamLength');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
if (streamLength > BlobConstants.MAX_BLOCK_SIZE) {
throw new Error(SR.INVALID_STREAM_LENGTH);
} else {
this._createBlock(blockId, container, blob, null, readStream, streamLength, options, callback);
}
};
/**
* Creates a new block to be committed as part of a blob.
*
* @this {BlobService}
* @param {string} blockId The block identifier.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|buffer} content The block content.
* @param {object} [options] The request options.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentMD5] The blob’s MD5 hash.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
* @return {undefined}
*/
BlobService.prototype.createBlockFromText = function (blockId, container, blob, content, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createBlockFromText', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content));
if (contentLength > BlobConstants.MAX_BLOCK_SIZE) {
throw new Error(SR.INVALID_TEXT_LENGTH);
} else {
this._createBlock(blockId, container, blob, content, null, contentLength, options, callback);
}
};
/**
* Creates a new block to be committed as part of a block blob.
* @ignore
*
* @this {BlobService}
* @param {string} blockId The block identifier.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|buffer} content The block content.
* @param (Stream) stream The stream to the data to store.
* @param {int} length The length of the stream or text to upload.
* @param {object} [options] The request options.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentMD5] The blob’s MD5 hash.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
* @return {undefined}
*/
BlobService.prototype._createBlock = function (blockId, container, blob, content, stream, length, options, callback) {
var resourceName = createResourceName(container, blob);
var self = this;
var startCreateBlock = function () {
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'block')
.withQueryOption(QueryStringConstants.BLOCK_ID, new Buffer(blockId).toString('base64'))
.withHeader(HeaderConstants.CONTENT_LENGTH, length);
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
if (!azureutil.objectIsNull(content)) {
self.performRequest(webResource, content, options, processResponseCallback);
} else {
self.performRequestOutputStream(webResource, stream, options, processResponseCallback);
}
};
if (azureutil.objectIsNull(options.contentMD5) && options.useTransactionalMD5) {
if (!azureutil.objectIsNull(content)) {
options.contentMD5 = azureutil.getContentMd5(content);
startCreateBlock();
} else {
azureutil.calculateMD5(stream, length, options, function (internalBuff) {
content = internalBuff;
length = internalBuff.length;
startCreateBlock();
});
}
} else {
startCreateBlock();
}
};
/**
* Writes a blob by specifying the list of block IDs that make up the blob.
* In order to be written as part of a blob, a block must have been successfully written to the server in a prior
* createBlock operation.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} blockList The block identifiers.
* @param {object} [options] The request options.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the blocklist information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.commitBlocks = function (container, blob, blockList, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('commitBlocks', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var blockListXml = BlockListResult.serialize(blockList);
var resourceName = createResourceName(container, blob);
var options = extend(true, {}, userOptions);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'blocklist')
.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(blockListXml))
.withBody(blockListXml);
BlobResult.setPropertiesFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
responseObject.list = null;
if (!responseObject.error) {
responseObject.list = blockList;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.list, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Retrieves the list of blocks that have been uploaded as part of a block blob.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlockListFilter} blocklisttype The type of block list to retrieve.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The source blob snapshot identifier.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the blocklist information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.listBlocks = function (container, blob, blocklisttype, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listBlocks', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var resourceName = createResourceName(container, blob);
var options = extend(true, {}, userOptions);
var webResource = WebResource.get(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'blocklist')
.withQueryOption(QueryStringConstants.BLOCK_LIST_TYPE, blocklisttype)
.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
BlobResult.setHeadersFromBlob(webResource, blob);
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
var processResponseCallback = function (responseObject, next) {
responseObject.blockListResult = null;
if (!responseObject.error) {
responseObject.blockListResult = BlockListResult.parse(responseObject.response.body.BlockList);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blockListResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Generate a random block id prefix
*/
BlobService.prototype.generateBlockIdPrefix = function () {
var prefix = Math.random().toString(16);
return azureutil.zeroPaddingString(prefix, 8);
};
/**
* Get a block id according to prefix and block number
*/
BlobService.prototype.getBlockId = function (prefix, number) {
return prefix + '-' + azureutil.zeroPaddingString(number, 6);
};
// Append blob methods
/**
* Creates an empty append blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.createOrReplaceAppendBlob = function (container, blob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createOrReplaceAppendBlob', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.APPEND)
.withHeader(HeaderConstants.LEASE_ID, options.leaseId)
.withHeader(HeaderConstants.CONTENT_LENGTH, 0);
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Creates a new append blob from a local file. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* If you want to append data to an already existing blob, please look at AppendFromLocalFile.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} localFileName The local path to the file to be uploaded.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.createAppendBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.APPEND, localFileName, optionsOrCallback, callback);
};
/**
* Uploads an append blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* If you want to append data to an already existing blob, please look at AppendFromStream.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {SpeedSummary} [options.speedSummary] The download tracker objects.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.createAppendBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.APPEND, stream, streamLength, optionsOrCallback, callback);
};
/**
* Uploads an append blob from a text string. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* If you want to append data to an already existing blob, please look at AppendFromText.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|object} text The blob text, as a string or in a Buffer.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
* @return {undefined}
*/
BlobService.prototype.createAppendBlobFromText = function (container, blob, text, optionsOrCallback, callback) {
return this._createBlobFromText(container, blob, BlobConstants.BlobTypes.APPEND, text, optionsOrCallback, callback);
};
/**
* Provides a stream to write to a new append blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs and true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.position] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName));
*/
BlobService.prototype.createWriteStreamToNewAppendBlob = function (container, blob, optionsOrCallback, callback) {
return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.APPEND, 0, true, optionsOrCallback, callback);
};
/**
* Provides a stream to write to an existing append blob. Assumes that the blob exists.
* If it does not, please create the blob using createAppendBlob before calling this method or use createWriteStreamToNewAppendBlob.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs and true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.position] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName));
*/
BlobService.prototype.createWriteStreamToExistingAppendBlob = function (container, blob, optionsOrCallback, callback) {
return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.APPEND, 0, false, optionsOrCallback, callback);
};
/**
* Appends to an append blob from a local file. Assumes the blob already exists on the service.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} localFileName The local path to the file to be uploaded.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.AppendFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('AppendFromLocalFile', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.string(localFileName, 'localFileName');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
fs.stat(localFileName, function (error, stat) {
if (error) {
callback(error);
} else {
var stream = new FileReadStream(localFileName, { calcContentMd5: options.storeBlobContentMD5 });
self._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, stat.size, options, callback);
}
});
return options.speedSummary;
};
/**
* Appends to an append blob from a stream. Assumes the blob already exists on the service.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {SpeedSummary} [options.speedSummary] The download tracker objects.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype.AppendFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
validate.validateArgs('_createBlobFromStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.exists(stream, 'stream');
v.value(streamLength, 'streamLength');
v.callback(callback);
});
return this._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, streamLength, options, callback);
};
/**
* Appends to an append blob from a text string. Assumes the blob already exists on the service.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|object} text The blob text, as a string or in a Buffer.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
* @return {undefined}
*/
BlobService.prototype.AppendFromText = function (container, blob, text, optionsOrCallback, callback) {
return this._uploadBlobFromText(false, container, blob, BlobConstants.BlobTypes.APPEND, text, optionsOrCallback, callback);
};
/**
* Creates a new block from a read stream to be appended to an append blob.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} readStream The read stream.
* @param {int} streamLength The stream length.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to.
* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentMD5] The blob’s MD5 hash.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.appendBlockFromStream = function (container, blob, readStream, streamLength, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('appendBlockFromStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.exists(readStream, 'readStream');
v.value(streamLength, 'streamLength');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
if (streamLength > BlobConstants.MAX_BLOCK_SIZE) {
throw new Error(SR.INVALID_STREAM_LENGTH);
} else {
this._appendBlock(container, blob, null, readStream, streamLength, options, callback);
}
};
/**
* Creates a new block from a text to be appended to an append blob.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|object} content The block text, as a string or in a Buffer.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to.
* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentMD5] The blob’s MD5 hash.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype.appendBlockFromText = function (container, blob, content, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('appendBlockFromText', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content));
if (contentLength > BlobConstants.MAX_BLOCK_SIZE) {
throw new Error(SR.INVALID_TEXT_LENGTH);
} else {
this._appendBlock(container, blob, content, null, contentLength, options, callback);
}
};
// Private methods
/**
* Creates a new blob (Block/Page/Append). If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlobType} blobType The blob type.
* @param {string} localFileName The local path to the file to be uploaded.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only)
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
*
* @return {SpeedSummary}
*
*/
BlobService.prototype._createBlobFromLocalFile = function (container, blob, blobType, localFileName, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('_createBlobFromLocalFile', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.blobTypeIsValid(blobType);
v.string(localFileName, 'localFileName');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.speedSummary = options.speedSummary || new SpeedSummary(blob);
var self = this;
var size = 0;
// Check the file size to determine the upload method: single request or chunks
fs.stat(localFileName, function (error, stat) {
if (error) {
callback(error);
} else {
size = stat.size;
self._createBlob(container, blob, blobType, size, options, creationCallback);
}
});
var creationCallback = function (createError, createBlob, createResponse) {
if (createError) {
callback(createError, createBlob, createResponse);
} else {
// Automatically detect the mime type
if (options.contentType === undefined) {
options.contentType = mime.lookup(localFileName);
}
var stream = new FileReadStream(localFileName, { calcContentMd5: options.storeBlobContentMD5 });
self._uploadBlobFromStream(true, container, blob, blobType, stream, size, options, callback);
}
};
return options.speedSummary;
};
/**
* Creates a new blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlobType} blobType The blob type.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The upload tracker objects.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only)
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._createBlobFromStream = function (container, blob, blobType, stream, streamLength, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('_createBlobFromStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.blobTypeIsValid(blobType);
v.exists(stream, 'stream');
v.value(streamLength, 'streamLength');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
var creationCallback = function (createError, createBlob, createResponse) {
if (createError) {
callback(createError, createBlob, createResponse);
} else {
self._uploadBlobFromStream(true, container, blob, blobType, stream, streamLength, options, callback);
}
};
this._createBlob(container, blob, blobType, streamLength, options, creationCallback);
return options.speedSummary;
};
/**
* Uploads a block blob or an append blob from a text string. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlobType} blobType The blob type.
* @param {string|buffer} content The blob text, as a string or in a Buffer.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* Use options.accessConditions = require('azure-storage').AccessCondition.generateIfNotExistsCondition()
* to avoid overwriting and instead throw an error if the blob exists.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
* @return {undefined}
*/
BlobService.prototype._createBlobFromText = function (container, blob, blobType, content, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('_createBlobFromText', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.blobTypeIsValid(blobType);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
var creationCallback = function (createError, createBlob, createResponse) {
if (createError) {
callback(createError, createBlob, createResponse);
} else {
self._uploadBlobFromText(true, container, blob, blobType, content, options, callback);
}
};
var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content));
this._createBlob(container, blob, blobType, contentLength, options, creationCallback);
return options.speedSummary;
};
/**
* Provides a stream to write to a block blob or an append blob.
*
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlobType} blobType The blob type.
* @param {int} length The blob length.
* @param {bool} createNewBlob Specifies whether create a new blob.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only)
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* The default value is false for page blobs and true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.position] The blob's content disposition. (x-ms-blob-content-disposition)
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback The callback function.
* @return {Stream}
*/
BlobService.prototype._createWriteStreamToBlob = function (container, blob, blobType, length, createNewBlob, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('_createWriteStreamToBlob', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.blobTypeIsValid(blobType);
});
var options = extend(true, {}, userOptions);
if (blobType === BlobConstants.BlobTypes.BLOCK) {
// default to true, unless explicitly set to false
options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true;
}
var stream = new ChunkStream({ calcContentMd5: options.storeBlobContentMD5 });
stream.pause(); //Immediately pause the stream in order to wait for the destination to getting ready
var self = this;
var createCallback = function (createError, createBlob, createResponse) {
if (createError) {
if (callback) {
callback(createError, createBlob, createResponse);
}
} else {
self._uploadBlobFromStream(createNewBlob, container, blob, blobType, stream, null, options, function (error, blob, response) {
if (error) {
stream.emit('error', error);
}
if (callback) {
callback(error, blob, response);
}
});
}
};
if (createNewBlob === true) {
this._createBlob(container, blob, blobType, length, options, createCallback);
} else {
createCallback();
}
return stream;
};
/**
* Upload blob content from a stream. Assumes the blob already exists.
*
* @ignore
*
* @this {BlobService}
* @param {bool} isNewBlob Specifies whether the blob is newly created.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlobType} blobType The blob type.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The upload tracker objects.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only)
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._uploadBlobFromStream = function (isNewBlob, container, blob, blobType, stream, streamLength, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
options.speedSummary = options.speedSummary || new SpeedSummary(blob);
if (blobType === BlobConstants.BlobTypes.BLOCK) {
// default to true, unless explicitly set to false
options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true;
}
stream.pause();
var self = this;
var startUpload = function () {
var putBlockBlobFromStream = function () {
var finalCallback = function (error, result, response) {
if (error) {
callback(error, result, response);
} else {
callback(error, blob, response);
}
};
if (streamLength > 0 && azureutil.objectIsNull(options.contentMD5) && options.storeBlobContentMD5) {
azureutil.calculateMD5(stream, self.singleBlobPutThresholdInBytes, options, function (internalBuff) {
self._putBlockBlob(container, blob, internalBuff, null, internalBuff.length, options, finalCallback);
});
stream.resume();
} else {
// Stream will resume when it has a pipe destination or a 'data' listener
self._putBlockBlob(container, blob, null, stream, streamLength, options, finalCallback);
}
};
if (streamLength === null || streamLength >= self.singleBlobPutThresholdInBytes || blobType !== BlobConstants.BlobTypes.BLOCK) {
var chunkStream = new ChunkStreamWithStream(stream, { calcContentMd5: options.storeBlobContentMD5 });
self._uploadContentFromChunkStream(container, blob, blobType, chunkStream, streamLength, options, callback);
} else {
putBlockBlobFromStream();
}
};
if (!isNewBlob) {
if (options.storeBlobContentMD5 && blobType !== BlobConstants.BlobTypes.BLOCK ) {
throw new Error(SR.MD5_NOT_POSSIBLE);
}
if (blobType === BlobConstants.BlobTypes.APPEND || (options.accessConditions && options.accessConditions.length > 0)) {
// Do a getBlobProperties right at the beginning for existing blobs and use the user passed in access conditions.
// So any pre-condition failure on the first block (in a strictly single writer scenario) is caught.
// This call also helps us get the append position to append to if the user hasn’t specified an access condition.
this.getBlobProperties(container, blob, options, function (error, properties) {
if (error) {
callback(error);
} else {
if (blobType === BlobConstants.BlobTypes.APPEND) {
options.appendPosition = properties.contentLength;
}
startUpload();
}
});
} else {
startUpload();
}
} else {
startUpload();
}
return options.speedSummary;
};
/**
* Upload blob content from a text. Assumes the blob already exists.
*
* @ignore
*
* @this {BlobService}
* @param {bool} isNewBlob Specifies whether the blob is newly created.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {BlobType} blobType The blob type.
* @param (string) content The blob text, as a string or in a Buffer.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The upload tracker objects.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only)
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._uploadBlobFromText = function (isNewBlob, container, blob, blobType, content, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
options.speedSummary = options.speedSummary || new SpeedSummary(blob);
options[HeaderConstants.CONTENT_TYPE] = 'text/plain;charset="utf-8"';
var self = this;
var startUpload = function () {
var operationFunc;
var length = Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content);
if (blobType === BlobConstants.BlobTypes.BLOCK) {
// default to true, unless explicitly set to false
options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true;
operationFunc = self._putBlockBlob;
if (length > BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES) {
throw new Error(SR.INVALID_BLOB_LENGTH);
}
} else if (blobType === BlobConstants.BlobTypes.APPEND) {
operationFunc = self._appendBlock;
if (length > BlobConstants.MAX_BLOCK_SIZE) {
throw new Error(SR.INVALID_TEXT_LENGTH);
}
}
var finalCallback = function (error, blobResult, response) {
if (blobType !== BlobConstants.BlobTypes.BLOCK) {
self.setBlobProperties(container, blob, options, function (error, blob, response) {
blob = extend(false, blob, blobResult);
callback(error, blob, response);
});
} else {
callback(error, blobResult, response);
}
};
operationFunc.call(self, container, blob, content, null, length, options, finalCallback);
};
if (!isNewBlob) {
if (options.storeBlobContentMD5 && blobType !== BlobConstants.BlobTypes.BLOCK ) {
throw new Error(SR.MD5_NOT_POSSIBLE);
}
if (blobType === BlobConstants.BlobTypes.APPEND || (options.accessConditions && options.accessConditions.length > 0)) {
// Do a getBlobProperties right at the beginning for existing blobs and use the user passed in access conditions.
// So any pre-condition failure on the first block (in a strictly single writer scenario) is caught.
// This call also helps us get the append position to append to if the user hasn’t specified an access condition.
this.getBlobProperties(container, blob, options, function (error, properties) {
if (error) {
callback(error);
} else {
if (blobType === BlobConstants.BlobTypes.APPEND) {
options.appendPosition = properties.contentLength;
}
startUpload();
}
});
}
} else {
if (!azureutil.objectIsNull(content) && azureutil.objectIsNull(options.contentMD5) && options.storeBlobContentMD5) {
options.contentMD5 = azureutil.getContentMd5(content);
}
startUpload();
}
};
/**
* Uploads a block blob from a stream.
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} text The blob text.
* @param (Stream) stream Stream to the data to store.
* @param {int} length The length of the stream or text to upload.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* information about the blob.
* `response` will contain information related to this operation.
* @return {undefined}
*
*/
BlobService.prototype._putBlockBlob = function (container, blob, text, stream, length, options, callback) {
if (!options.speedSummary) {
options.speedSummary = new SpeedSummary(blob);
}
var speedSummary = options.speedSummary;
speedSummary.totalSize = length;
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream')
.withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.BLOCK)
.withHeader(HeaderConstants.CONTENT_LENGTH, length);
if (!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.contentMD5) && options.useTransactionalMD5) {
options.contentMD5 = azureutil.getContentMd5(text);
}
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
if (options.metadata) {
responseObject.blobResult.metadata = options.metadata;
}
}
var finalCallback = function (returnObject) {
if (!returnObject || !returnObject.error) {
speedSummary.increment(length);
}
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
if (!azureutil.objectIsNull(text)) {
this.performRequest(webResource, text, options, processResponseCallback);
} else {
this.performRequestOutputStream(webResource, stream, options, processResponseCallback);
}
return options.speedSummary;
};
/**
* Appends a new block to an append blob.
*
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string|buffer} content The block content.
* @param (Stream) stream The stream to the data to store.
* @param {int} length The length of the stream or content to upload.
* @param {object} [options] The request options.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry.
* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to.
* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {string} [options.contentMD5] The blob’s MD5 hash.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
* `response` will contain information related to this operation.
*/
BlobService.prototype._appendBlock = function (container, blob, content, stream, length, options, callback) {
var speedSummary = options.speedSummary || new SpeedSummary(blob);
speedSummary.totalSize = length;
var self = this;
var startAppendBlock = function () {
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'appendblock')
.withHeader(HeaderConstants.CONTENT_LENGTH, length)
.withHeader(HeaderConstants.BLOB_CONDITION_MAX_SIZE, options.maxBlobSize)
.withHeader(HeaderConstants.BLOB_CONDITION_APPEND_POSITION, options.appendPosition || 0);
BlobResult.setHeadersFromBlob(webResource, options);
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
if (!returnObject || !returnObject.error) {
speedSummary.increment(length);
}
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
if (!azureutil.objectIsNull(content)) {
self.performRequest(webResource, content, options, processResponseCallback);
} else {
self.performRequestOutputStream(webResource, stream, options, processResponseCallback);
}
};
if (azureutil.objectIsNull(options.contentMD5) && options.useTransactionalMD5) {
if (!azureutil.objectIsNull(content)) {
options.contentMD5 = azureutil.getContentMd5(content);
startAppendBlock();
} else {
azureutil.calculateMD5(stream, length, options, function (internalBuff) {
content = internalBuff;
length = internalBuff.length;
startAppendBlock();
});
}
} else {
startAppendBlock();
}
return options.speedSummary;
};
/**
* Creates and dispatches lease requests.
* @ignore
*
* @this {BlobService}
* @param {object} webResource The web resource.
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} leaseId The lease identifier. Required to renew, change or release the lease.
* @param {string} leaseAction The lease action (BlobConstants.LeaseOperation.*). Required.
* @param {object} userOptions The request options.
* @param {int} [userOptions.leaseBreakPeriod] The lease break period.
* @param {string} [userOptions.leaseDuration] The lease duration. Default is never to expire.
* @param {string} [userOptions.proposedLeaseId] The proposed lease identifier. This is required for the CHANGE lease action.
* @param {LocationMode} [userOptions.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {object} [userOptions.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {int} [userOptions.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [userOptions.maximumExecutionTimeInMs]The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(error, lease, response)} callback `error` will contain information
* if an error occurs; otherwise `lease` will contain
* the lease information.
* `response` will contain information related to this operation.
*/
BlobService.prototype._leaseImpl = function (container, blob, leaseId, leaseAction, options, callback) {
var webResource;
if (!azureutil.objectIsNull(blob)) {
validate.validateArgs('_leaseImpl', function (v) {
v.string(blob, 'blob');
});
var resourceName = createResourceName(container, blob);
webResource = WebResource.put(resourceName);
} else {
webResource = WebResource.put(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container');
}
webResource.withQueryOption(QueryStringConstants.COMP, 'lease')
.withHeader(HeaderConstants.LEASE_ID, leaseId)
.withHeader(HeaderConstants.LEASE_ACTION, leaseAction.toLowerCase())
.withHeader(HeaderConstants.LEASE_BREAK_PERIOD, options.leaseBreakPeriod)
.withHeader(HeaderConstants.PROPOSED_LEASE_ID, options.proposedLeaseId)
.withHeader(HeaderConstants.LEASE_DURATION, options.leaseDuration);
var processResponseCallback = function (responseObject, next) {
responseObject.leaseResult = null;
if (!responseObject.error) {
responseObject.leaseResult = new LeaseResult(container, blob);
responseObject.leaseResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.leaseResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Updates a page blob from text.
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} text The text string.
* @param {Stream} readStream The read stream.
* @param {int} rangeStart The range start.
* @param {int} rangeEnd The range end.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The target blob lease identifier.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(error, pageBlob, response)} callback `error` will contain information
* if an error occurs; otherwise `pageBlob` will contain
* the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype._createPages = function (container, blob, text, readStream, rangeStart, rangeEnd, options, callback) {
var request = this._updatePageBlobPagesImpl(container, blob, rangeStart, rangeEnd, BlobConstants.PageWriteOptions.UPDATE, options);
// At this point, we have already validated that the range is less than 4MB. Therefore, we just need to calculate the contentMD5 if required.
// Even when this is called from the createPagesFromStream method, it is pre-buffered and called with text.
if (!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.contentMD5) && options.useTransactionalMD5) {
request.withHeader(HeaderConstants.CONTENT_MD5, azureutil.getContentMd5(text));
}
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
if (!azureutil.objectIsNull(text)) {
this.performRequest(request, text, options, processResponseCallback);
} else {
this.performRequestOutputStream(request, readStream, options, processResponseCallback);
}
};
/**
* @ignore
*/
BlobService.prototype._updatePageBlobPagesImpl = function (container, blob, rangeStart, rangeEnd, writeMethod, options) {
if (rangeStart && rangeStart % BlobConstants.PAGE_SIZE !== 0) {
throw new Error(SR.INVALID_PAGE_START_OFFSET);
}
if (rangeEnd && (rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) {
throw new Error(SR.INVALID_PAGE_END_OFFSET);
}
// this is necessary if this is called from _uploadContentFromChunkStream->_createPages
if (!options) {
options = {};
}
options.rangeStart = rangeStart;
options.rangeEnd = rangeEnd;
options.contentLength = writeMethod === BlobConstants.PageWriteOptions.UPDATE ? (rangeEnd - rangeStart) + 1 : 0;
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'page')
.withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream')
.withHeader(HeaderConstants.PAGE_WRITE, writeMethod);
BlobResult.setHeadersFromBlob(webResource, options);
return webResource;
};
/**
* Uploads blob content from a stream.
* For block blob, it creates a new block to be committed.
* For page blob, it writes a range of pages.
* For append blob, it appends a new block.
*
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} blobType The blob type.
* @param (Stream) stream Stream to the data to store.
* @param {int} streamLength The length of the stream to upload.
* @param {object|function} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The download tracker objects;
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count.
* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to.
* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions.
* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id.
* @param {string} [options.leaseId] The lease identifier.
* @param {object} [options.metadata] The metadata key/value pairs.
* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads.
* @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream.
* @param {string} [options.contentEncoding] The content encodings that have been applied to the blob.
* @param {string} [options.contentLanguage] The natural languages used by this resource.
* @param {string} [options.contentMD5] The MD5 hash of the blob content.
* @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it.
* @param {string} [options.contentDisposition] The blob's content disposition.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {function(error, null)} callback The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._uploadContentFromChunkStream = function (container, blob, blobType, chunkStream, streamLength, options, callback) {
this.logger.debug(util.format('_uploadContentFromChunkStream for blob %s', blob));
var apiName;
var isBlockBlobUpload;
var isPageBlobUpload;
var isAppendBlobUpload;
var sizeLimitation;
var originalContentMD5 = options.contentMD5;
var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount;
if (blobType == BlobConstants.BlobTypes.BLOCK) {
apiName = 'createBlockFromText';
isBlockBlobUpload = true;
sizeLimitation = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
} else if (blobType == BlobConstants.BlobTypes.PAGE) {
apiName = '_createPages';
isPageBlobUpload = true;
sizeLimitation = BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES;
} else if (blobType == BlobConstants.BlobTypes.APPEND) {
apiName = 'appendBlockFromText';
isAppendBlobUpload = true;
parallelOperationThreadCount = 1;
sizeLimitation = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
} else {
var error = new Error(util.format('Unknown blob type %s', blobType));
callback(error);
return;
}
this._setOperationExpiryTime(options);
// initialize the speed summary
var speedSummary = options.speedSummary || new SpeedSummary(blob);
speedSummary.totalSize = streamLength;
// initialize chunk allocator
var allocator = new ChunkAllocator(sizeLimitation, options.parallelOperationThreadCount, { logger: this.logger });
// if this is a FileReadStream, set the allocator on that stream
if (chunkStream._stream && chunkStream._stream.setMemoryAllocator) {
chunkStream._stream.setMemoryAllocator(allocator);
}
// initialize batch operations
var batchOperations = new BatchOperation(apiName, { callInOrder: isAppendBlobUpload, callbackInOrder: isAppendBlobUpload, logger : this.logger });
batchOperations.setConcurrency(parallelOperationThreadCount);
// initialize options
var rangeOptions = {
leaseId: options.leaseId,
timeoutIntervalInMs: options.timeoutIntervalInMs,
operationExpiryTime: options.operationExpiryTime,
maxBlobSize: options.maxBlobSize,
appendPosition: options.appendPosition || 0,
initialAppendPosition: options.appendPosition || 0,
absorbConditionalErrorsOnRetry: options.absorbConditionalErrorsOnRetry
};
// initialize block blob variables
var blockIdPrefix = options.blockIdPrefix || this.generateBlockIdPrefix();
var blockCount = 0;
var blockIds = [];
var blobResult = {};
var self = this;
chunkStream.on('data', function (data, range) {
var operation = null;
var full = false;
var autoIncrement = speedSummary.getAutoIncrementFunction(data.length);
if (data.length > sizeLimitation) {
throw new Error(util.format(SR.EXCEEDED_SIZE_LIMITATION, sizeLimitation, data.length));
}
if (options.useTransactionalMD5) {
//calculate content md5 for the current uploading block data
var contentMD5 = azureutil.getContentMd5(data);
rangeOptions.contentMD5 = contentMD5;
}
var uploadBlockBlobChunk = function () {
var blockId = self.getBlockId(blockIdPrefix, blockCount);
blockIds.push(blockId);
operation = new BatchOperation.RestOperation(self, apiName, blockId, container, blob, data, rangeOptions, function (error) {
if (!error) {
autoIncrement();
}
allocator.releaseBuffer(data);
data = null;
});
blockCount++;
};
var uploadPageBlobChunk = function () {
if (azureutil.isBufferAllZero(data)) {
self.logger.debug(util.format('Skip upload data from %s bytes to %s bytes to blob %s', range.start, range.end, blob));
speedSummary.increment(data.length);
} else {
self.logger.debug(util.format('Upload data from %s bytes to %s bytes to blob %s', range.start, range.end, blob));
operation = new BatchOperation.RestOperation(self, apiName, container, blob, data, null, range.start, range.end, rangeOptions, function (error) {
if (!error) {
autoIncrement();
} else {
self.logger.debug(util.format('Error: %s', require('util').inspect(error)));
}
allocator.releaseBuffer(data);
data = null;
});
}
};
var uploadAppendBlobChunk = function () {
rangeOptions.appendPosition = Number(rangeOptions.initialAppendPosition) + Number(range.start);
// We cannot differentiate between max size condition failing only in the retry versus failing in the first attempt and retry.
// So we will eliminate the latter and handle the former in the append operation callback.
if (options.maxBlobSize && rangeOptions.appendPosition + data.length > options.maxBlobSize) {
throw new Error(SR.MAX_BLOB_SIZE_CONDITION_NOT_MEET);
}
operation = new BatchOperation.RestOperation(self, apiName, container, blob, data, rangeOptions, function (error, currentBlob) {
if (!error) {
autoIncrement();
}
blobResult = currentBlob;
allocator.releaseBuffer(data);
data = null;
});
};
if (isBlockBlobUpload) {
uploadBlockBlobChunk();
} else if (isAppendBlobUpload) {
uploadAppendBlobChunk();
} else if (isPageBlobUpload) {
uploadPageBlobChunk();
}
if (operation) {
full = batchOperations.addOperation(operation);
operation = null;
if (full) {
self.logger.debug('File stream paused');
chunkStream.pause();
}
}
});
chunkStream.on('end', function () {
self.logger.debug(util.format('File read stream ended for blob %s', blob));
batchOperations.enableComplete();
});
batchOperations.on('drain', function () {
self.logger.debug('file stream resume');
chunkStream.resume();
});
batchOperations.on('end', function (error) {
self.logger.debug('batch operations commited');
speedSummary = null;
if (error) {
callback(error);
return;
}
if (originalContentMD5) {
options.contentMD5 = originalContentMD5;
} else if (options.storeBlobContentMD5) {
options.contentMD5 = chunkStream.getContentMd5('base64');
}
if (isBlockBlobUpload) {
//commit block list
var blockList = { 'UncommittedBlocks': blockIds };
self.commitBlocks(container, blob, blockList, options, function (error, blockList, response) {
self.logger.debug(util.format('Blob %s committed', blob));
if (error) {
chunkStream.finish();
callback(error);
} else {
blobResult['commmittedBlocks'] = blockIds;
chunkStream.finish();
callback(error, blobResult, response);
}
});
} else {
// upload page blob or append blob completely
self.setBlobProperties(container, blob, options, function (error, blob, response) {
chunkStream.finish();
blob = extend(false, blob, blobResult);
callback(error, blob, response);
});
}
});
return speedSummary;
};
/**
* Checks whether or not a container exists on the service.
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} primaryOnly If true, the request will be executed against the primary storage location.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(error, containerExists, response)} callback `error` will contain information
* if an error occurs; otherwise `containerExists` will contain
* be true if the container exists, or false if the container does not exist.
* `response` will contain information related to this operation.
*/
BlobService.prototype._doesContainerExist = function (container, primaryOnly, options, callback) {
var webResource = WebResource.head(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
if (primaryOnly === false) {
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
}
var processResponseCallback = function (responseObject, next) {
if (!responseObject.error) {
responseObject.exists = true;
} else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
responseObject.error = null;
responseObject.exists = false;
responseObject.response.isSuccessful = true;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.exists, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Checks whether or not a blob exists on the service.
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} primaryOnly If true, the request will be executed against the primary storage location.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The lease identifier.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(error, blobExists, response)} callback `error` will contain information
* if an error occurs; otherwise `blobExists` will
* be true if the blob exists, or false if the blob does not exist.
* `response` will contain information related to this operation.
*/
BlobService.prototype._doesBlobExist = function (container, blob, primaryOnly, options, callback) {
var resourceName = createResourceName(container, blob);
var webResource = WebResource.head(resourceName)
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
if (primaryOnly === false) {
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
}
var processResponseCallback = function (responseObject, next) {
if (!responseObject.error) {
responseObject.exists = true;
} else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
responseObject.error = null;
responseObject.exists = false;
responseObject.response.isSuccessful = true;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.exists, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* @ignore
*/
BlobService.prototype._setBlobPropertiesHelper = function (settings) {
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(settings.container, settings.blob);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
settings.callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(settings.webResource, null, settings.options, processResponseCallback);
};
/**
* @ignore
*/
BlobService.prototype._validateLengthAndMD5 = function (options, responseObject) {
var storedMD5 = responseObject.response.headers[Constants.HeaderConstants.CONTENT_MD5];
var contentLength;
if (!azureutil.objectIsNull(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH])) {
contentLength = parseInt(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH], 10);
}
// If the user has not specified this option, the default value should be false.
if (azureutil.objectIsNull(options.disableContentMD5Validation)) {
options.disableContentMD5Validation = false;
}
// None of the below cases should be retried. So set the error in every case so the retry policy filter handle knows that it shouldn't be retried.
if (options.disableContentMD5Validation === false && options.useTransactionalMD5 === true && azureutil.objectIsNull(storedMD5)) {
responseObject.error = new Error(SR.MD5_NOT_PRESENT_ERROR);
responseObject.retryable = false;
}
// Validate length and if required, MD5.
// If getBlobToText called this method, then the responseObject.length and responseObject.contentMD5 are not set. Calculate them first using responseObject.response.body and then validate.
if (azureutil.objectIsNull(responseObject.length)) {
if (typeof responseObject.response.body == 'string') {
responseObject.length = Buffer.byteLength(responseObject.response.body);
} else if (Buffer.isBuffer(responseObject.response.body)) {
responseObject.length = responseObject.response.body.length;
}
}
if (!azureutil.objectIsNull(contentLength) && responseObject.length !== contentLength) {
responseObject.error = new Error(SR.CONTENT_LENGTH_MISMATCH);
responseObject.retryable = false;
}
if (options.disableContentMD5Validation === false && azureutil.objectIsNull(responseObject.contentMD5)) {
responseObject.contentMD5 = azureutil.getContentMd5(responseObject.response.body);
}
if (options.disableContentMD5Validation === false && !azureutil.objectIsNull(storedMD5) && storedMD5 !== responseObject.contentMD5) {
responseObject.error = new Error(util.format(SR.HASH_MISMATCH, storedMD5, responseObject.contentMD5));
responseObject.retryable = false;
}
};
/**
* @ignore
*/
BlobService.prototype._setRangeContentMD5Header = function (webResource, options) {
if (!azureutil.objectIsNull(options.rangeStart) && options.useTransactionalMD5) {
if (azureutil.objectIsNull(options.rangeEnd)) {
throw new Error(util.format(SR.ARGUMENT_NULL_OR_EMPTY, options.rangeEndHeader));
}
var size = parseInt(options.rangeEnd, 10) - parseInt(options.rangeStart, 10) + 1;
if (size > BlobConstants.MAX_RANGE_GET_SIZE_WITH_MD5) {
throw new Error(SR.INVALID_RANGE_FOR_MD5);
} else {
webResource.withHeader(HeaderConstants.RANGE_GET_CONTENT_MD5, 'true');
}
}
};
/**
* Downloads a blockblob or pageblob into a range stream.
* @ignore
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} blobType The type of blob to create: block blob or page blob.
* @param {Stream} writeStream The write stream.
* @param {object} [options] The request options.
* @param {SpeedSummary} [options.speedSummary] The upload tracker objects.
* @param {int} [options.parallelOperationThreadCount] Parallel operation thread count
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the blob information.
* `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype._getBlobToRangeStream = function (container, blob, blobType, writeStream, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
validate.validateArgs('_getBlobToRangeStream', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.containerNameIsValid(container);
v.blobNameIsValid(container, blob);
v.blobTypeIsValid(blobType);
v.callback(callback);
});
var rangeStream = null;
var isPageBlobDownload = true;
if (blobType == BlobConstants.BlobTypes.PAGE) {
rangeStream = new PageRangeStream(this, container, blob, options);
} else if (blobType == BlobConstants.BlobTypes.APPEND) {
rangeStream = new RangeStream(this, container, blob, options);
isPageBlobDownload = false;
} else if (blobType == BlobConstants.BlobTypes.BLOCK) {
rangeStream = new BlockRangeStream(this, container, blob, options);
isPageBlobDownload = false;
}
if (!options.speedSummary) {
options.speedSummary = new SpeedSummary(blob);
}
var speedSummary = options.speedSummary;
var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount;
var batchOperations = new BatchOperation('getBlobInRanges', { callbackInOrder: true, logger : this.logger });
batchOperations.setConcurrency(parallelOperationThreadCount);
var self = this;
var checkMD5sum = !options.disableContentMD5Validation;
var md5Hash = null;
if (checkMD5sum) {
md5Hash = crypto.createHash('md5');
}
var savedBlobResult = null;
var savedBlobResponse = null;
rangeStream.on('range', function (range) {
if (!speedSummary.totalSize) {
speedSummary.totalSize = rangeStream.rangeSize;
}
var requestOptions = {
rangeStart : range.start,
rangeEnd : range.end,
responseEncoding : null //Use Buffer to store the response data
};
var rangeSize = range.size;
requestOptions.timeoutIntervalInMs = options.timeoutIntervalInMs;
if (range.dataSize === 0) {
if (isPageBlobDownload) {
var autoIncrement = speedSummary.getAutoIncrementFunction(rangeSize);
//No operation to do and only wait for write zero to file in callback
var writeZeroOperation = new BatchOperation.CommonOperation(BatchOperation.noOperation, function (error) {
if (error) return;
var bufferAvailable = azureutil.writeZerosToStream(writeStream, rangeSize, md5Hash, autoIncrement);
//There is no need to pause the rangestream since we can perform http request and write disk at the same time
self.logger.debug(util.format('Write %s bytes Zero from %s to %s', rangeSize, range.start, range.end));
if (!bufferAvailable) {
self.logger.debug('Write stream is full and pause batch operation');
batchOperations.pause();
}
});
batchOperations.addOperation(writeZeroOperation);
} else {
self.logger.debug(util.format('Can not read %s bytes to %s bytes of blob %s', range.start, range.end, blob));
}
return;
}
if (range.start > range.end) {
return;
}
var operation = new BatchOperation.RestOperation(self, 'getBlobToText', container, blob, requestOptions, function (error, content, blobResult, response) {
if (!error) {
if (rangeSize !== content.length) {
self.logger.warn(util.format('Request %s bytes, but server returns %s bytes', rangeSize, content.length));
}
//Save one of the succeeded callback parameters and use them at the final callback
if (!savedBlobResult) {
savedBlobResult = blobResult;
}
if (!savedBlobResponse) {
savedBlobResponse = response;
}
var autoIncrement = speedSummary.getAutoIncrementFunction(content.length);
var bufferAvailable = writeStream.write(content, autoIncrement);
if (!bufferAvailable) {
self.logger.debug('Write stream is full and pause batch operation');
batchOperations.pause();
}
if (md5Hash) {
md5Hash.update(content);
}
content = null;
}
});
var full = batchOperations.addOperation(operation);
if (full) {
self.logger.debug('Pause range stream');
rangeStream.pause();
}
});
rangeStream.on('end', function () {
self.logger.debug('Range stream has ended.');
batchOperations.enableComplete();
});
batchOperations.on('drain', function () {
self.logger.debug('Resume range stream');
rangeStream.resume();
});
writeStream.on('drain', function () {
self.logger.debug('Resume batch operations');
batchOperations.resume();
});
batchOperations.on('end', function (error) {
self.logger.debug('Download completed!');
if (error) {
callback(error);
return;
} else {
writeStream.end(function () {
self.logger.debug('Write stream has ended');
if (writeStream.close) {
writeStream.close();
}
if (!savedBlobResult) {
savedBlobResult = {};
}
savedBlobResult.contentMD5 = options.contentMD5;
savedBlobResult.clientSideContentMD5 = null;
if (md5Hash) {
savedBlobResult.clientSideContentMD5 = md5Hash.digest('base64');
}
callback(error, savedBlobResult, savedBlobResponse);
});
}
});
var listOptions = {
timeoutIntervalInMs : options.timeoutIntervalInMs,
snapshotId : options.snapshotId,
leaseId : options.leaseId
};
rangeStream.list(listOptions);
return speedSummary;
};
/**
* Downloads a blockblob or pageblob into a stream.
* @ignore
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {Stream} writeStream The write stream.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype._getBlobToStream = function (container, blob, writeStream, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
var resourceName = createResourceName(container, blob);
var webResource = WebResource.get(resourceName).withRawResponse();
var options = extend(true, {}, userOptions);
webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
BlobResult.setHeadersFromBlob(webResource, options);
this._setRangeContentMD5Header(webResource, options);
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.blobResult = null;
if (!responseObject.error) {
responseObject.blobResult = new BlobResult(container, blob);
responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
self._validateLengthAndMD5(options, responseObject);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.blobResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequestInputStream(webResource, null, writeStream, options, processResponseCallback);
};
/**
* Downloads a blob into a file.
* @ignore
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} localFileName The local path to the file to be downloaded.
* @param {object} [options] The request options.
* @param {string} [options.snapshotId] The snapshot identifier.
* @param {string} [options.leaseId] The lease identifier.
* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range.
* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range.
* @param {object} [options.accessConditions] The access conditions. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the blob information.
* `response` will contain information related to this operation.
*/
BlobService.prototype._getBlobToLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
var writeStream = fs.createWriteStream(localFileName, { 'highWaterMark': BlobConstants.MAX_QUEUED_WRITE_DISK_BUFFER_SIZE });
this.getBlobToStream(container, blob, writeStream, options, function (error, responseBlob, response) {
if (error) {
if (azureutil.pathExistsSync(localFileName)) {
// make sure writeStream is closed / destroyed to avoid locking issues
if (writeStream.close) {
writeStream.close();
}
// If the download failed from the beginning, remove the file.
fs.unlink(localFileName, function () {
callback(error, responseBlob, response);
});
return;
}
}
callback(error, responseBlob, response);
});
};
/**
* Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container.
* @ignore
* @this {BlobService}
* @param {string} container The container name.
* @param {string} prefix The prefix of the blob name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {ListBlobTypes} listBlobType Specifies the item type of the results.
* @param {object} [options] The request options.
* @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs'). Multiple values can be added separated with a comma (,)
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs]The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain
* the entries of blobs and the continuation token for the next listing operation.
* `response` will contain information related to this operation.
*/
BlobService.prototype._listBlobsOrDircotriesSegmentedWithPrefix = function (container, prefix, currentToken, listBlobType, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listBlobsSegmented', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.get(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withQueryOption(QueryStringConstants.COMP, 'list')
.withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
.withQueryOptions(options,
QueryStringConstants.DELIMITER,
QueryStringConstants.INCLUDE);
if (!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
}
webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.listBlobsResult = null;
if (!responseObject.error) {
responseObject.listBlobsResult = {
entries: null,
continuationToken: null
};
responseObject.listBlobsResult.entries = [];
var results = [];
if (listBlobType == BlobConstants.ListBlobTypes.Directory && responseObject.response.body.EnumerationResults.Blobs.BlobPrefix) {
results = responseObject.response.body.EnumerationResults.Blobs.BlobPrefix;
if (!_.isArray(results)) {
results = [results];
}
} else if (listBlobType == BlobConstants.ListBlobTypes.Blob && responseObject.response.body.EnumerationResults.Blobs.Blob) {
results = responseObject.response.body.EnumerationResults.Blobs.Blob;
if (!_.isArray(results)) {
results = [results];
}
}
results.forEach(function (currentBlob) {
var blobResult = BlobResult.parse(currentBlob);
responseObject.listBlobsResult.entries.push(blobResult);
});
if (responseObject.response.body.EnumerationResults.NextMarker) {
responseObject.listBlobsResult.continuationToken = {
nextMarker: null,
targetLocation: null
};
responseObject.listBlobsResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
responseObject.listBlobsResult.continuationToken.targetLocation = responseObject.targetLocation;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.listBlobsResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Create a new blob.
* @ignore
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param (BlobType) blobType The blob type.
* @param {int} size The blob size.
* @param {object} [options] The request options.
* @param {errorOrResult} callback The callback which operates on the specific blob.
*/
BlobService.prototype._createBlob = function (container, blob, blobType, size, options, creationCallback) {
if (blobType == BlobConstants.BlobTypes.APPEND) {
this.createOrReplaceAppendBlob(container, blob, options, function (createError, createResponse) {
creationCallback(createError, null, createResponse);
});
} else if (blobType == BlobConstants.BlobTypes.PAGE) {
this.createPageBlob(container, blob, size, options, function (createError) {
creationCallback(createError);
});
} else if (blobType == BlobConstants.BlobTypes.BLOCK) {
creationCallback();
}
};
/**
* The callback for {BlobService~getBlobToText}.
* @typedef {function} BlobService~blobToText
* @param {object} error If an error occurs, the error information.
* @param {string} text The text returned from the blob.
* @param {object} blockBlob Information about the blob.
* @param {object} response Information related to this operation.
*/
BlobService.SpeedSummary = SpeedSummary;
module.exports = BlobService;
| {
"content_hash": "1591363df16e764ac238c8763a1ab087",
"timestamp": "",
"source": "github",
"line_count": 5583,
"max_line_length": 250,
"avg_line_length": 70.86046928174817,
"alnum_prop": 0.5962706072080362,
"repo_name": "badescuga/azure-storage-node",
"id": "6f864e1e72a7665663f1f849ac033beec4263525",
"size": "395636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/services/blob/blobservice.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "2874628"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="1000"
android:fromYDelta="-100%p"
android:toYDelta="1" />
</set> | {
"content_hash": "057d37ac0ceda8f764f5644bea56a6c7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 65,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.618421052631579,
"repo_name": "S1lv10Fr4gn4n1/example-android",
"id": "37c8a4f638fb4596a3eccb791f112a6df75c404f",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TestListviewEffects/res/anim/slide_in_top.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "2881"
},
{
"name": "Java",
"bytes": "79323"
}
],
"symlink_target": ""
} |
package libkb
// OSVersionAndBuild returns OS version, and build too on some platforms
func OSVersionAndBuild() (string, string, error) {
productVersion, err := execToString("/usr/bin/sw_vers", []string{"-productVersion"})
if err != nil {
return "", "", err
}
buildVersion, err := execToString("/usr/bin/sw_vers", []string{"-buildVersion"})
if err != nil {
return productVersion, "", err
}
return productVersion, buildVersion, nil
}
| {
"content_hash": "37d83487f5f254f8ea16a6b9bf978d10",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 85,
"avg_line_length": 29.733333333333334,
"alnum_prop": 0.695067264573991,
"repo_name": "keybase/client",
"id": "96682805739ca7d6154626961b834afa8ce52380",
"size": "482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "go/libkb/osv_darwin.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "17403"
},
{
"name": "C",
"bytes": "183175"
},
{
"name": "C++",
"bytes": "26935"
},
{
"name": "CMake",
"bytes": "2524"
},
{
"name": "CSS",
"bytes": "46433"
},
{
"name": "CoffeeScript",
"bytes": "28635"
},
{
"name": "Dockerfile",
"bytes": "19841"
},
{
"name": "Go",
"bytes": "32360664"
},
{
"name": "HTML",
"bytes": "7113636"
},
{
"name": "Java",
"bytes": "144690"
},
{
"name": "JavaScript",
"bytes": "113705"
},
{
"name": "Makefile",
"bytes": "8579"
},
{
"name": "Objective-C",
"bytes": "1419995"
},
{
"name": "Objective-C++",
"bytes": "34802"
},
{
"name": "Perl",
"bytes": "2673"
},
{
"name": "Python",
"bytes": "25189"
},
{
"name": "Roff",
"bytes": "108890"
},
{
"name": "Ruby",
"bytes": "38112"
},
{
"name": "Shell",
"bytes": "186628"
},
{
"name": "Starlark",
"bytes": "1928"
},
{
"name": "Swift",
"bytes": "217"
},
{
"name": "TypeScript",
"bytes": "2493"
},
{
"name": "XSLT",
"bytes": "914"
}
],
"symlink_target": ""
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.24 at 02:08:17 PM BST
//
package com.oracle.xmlns.apps.marketing.leadmgmt.leads.leadservice.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.oracle.xmlns.apps.marketing.leadmgmt.leads.leadservice.MklLeadTcMembers;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="result" type="{http://xmlns.oracle.com/apps/marketing/leadMgmt/leads/leadService/}MklLeadTcMembers"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"result"
})
@XmlRootElement(name = "updateSalesLeadContactAsyncResponse")
public class UpdateSalesLeadContactAsyncResponse {
@XmlElement(required = true)
protected MklLeadTcMembers result;
/**
* Gets the value of the result property.
*
* @return
* possible object is
* {@link MklLeadTcMembers }
*
*/
public MklLeadTcMembers getResult() {
return result;
}
/**
* Sets the value of the result property.
*
* @param value
* allowed object is
* {@link MklLeadTcMembers }
*
*/
public void setResult(MklLeadTcMembers value) {
this.result = value;
}
}
| {
"content_hash": "86c47f71963ec429be9e504ce9effb56",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 130,
"avg_line_length": 29.694444444444443,
"alnum_prop": 0.6524789522918616,
"repo_name": "delkyd/Oracle-Cloud",
"id": "b347427e140ebeca03054f8820258d3cf8abeb4c",
"size": "2138",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "PaaS_SaaS_Accelerator_RESTFulFacade/XJC_Beans/src/com/oracle/xmlns/apps/marketing/leadmgmt/leads/leadservice/types/UpdateSalesLeadContactAsyncResponse.java",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "810"
},
{
"name": "C#",
"bytes": "2922162"
},
{
"name": "CSS",
"bytes": "405502"
},
{
"name": "HTML",
"bytes": "2487"
},
{
"name": "Java",
"bytes": "33061859"
},
{
"name": "JavaScript",
"bytes": "43011"
},
{
"name": "PLSQL",
"bytes": "48918"
}
],
"symlink_target": ""
} |
@import url('auth/auth-buttons.css');
body {
font: 14px sans-serif;
}
#login ul.login-buttons {
margin: 0;
padding: 0;
list-style: none;
}
#login ul.login-buttons li {
margin: 5px 0;
}
#account #user-response {
overflow: auto;
white-space: normal;
} | {
"content_hash": "30a3f33a5956b76aee8dfd2b920e17da",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 37,
"avg_line_length": 14.05,
"alnum_prop": 0.6156583629893239,
"repo_name": "dylansmith/express-passport-demo",
"id": "6738e179284874b38c15de6930ab3c06a2c8f6f3",
"size": "281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/css/base.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "281"
},
{
"name": "JavaScript",
"bytes": "8337"
}
],
"symlink_target": ""
} |
@import "../../../framework/themes/default.css";
.icon.home { -webkit-mask-image: url(home_icon.png); vertical-align:middle; margin-top: -4px; } | {
"content_hash": "52f7a6b69f0351c2831327796bd1bb87",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 95,
"avg_line_length": 48.333333333333336,
"alnum_prop": 0.6827586206896552,
"repo_name": "nktpro/MooTouch",
"id": "b3cd2181e4e4dd22648523bf78bdd4143f03fd6d",
"size": "145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/navigation/themes/sample.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "556138"
},
{
"name": "PHP",
"bytes": "17996"
}
],
"symlink_target": ""
} |
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.MainActivity"
tools:ignore="MergeRootFrame" />
| {
"content_hash": "e769a23fd43b3de834797ee0d1881de7",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 71,
"avg_line_length": 46.142857142857146,
"alnum_prop": 0.7275541795665634,
"repo_name": "openpizza/openpizza-android",
"id": "d2e5c5b21d6006de153fcc1d314e92238fd57c24",
"size": "323",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "res/layout/activity_main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "817"
},
{
"name": "Java",
"bytes": "83341"
}
],
"symlink_target": ""
} |
<?php
class jChat
{
###############################################################################################
#### Properties
###############################################################################################
public $clientID;
public $client;
public $serverID;
public $server;
public $attachmentPath;
public $emoticons;
// users table from same database
public $users_table;
public $users_usernameField;
public $user_idField;
###############################################################################################
#### Methods
###############################################################################################
/******************************************************************
* Read Context
*******************************************************************/
public function __construct($db_server, $db_username, $db_password, $db_name, $table)
{
// Set Internal Variables
$this->db_server = $db_server;
$this->db_username = $db_username;
$this->db_password = $db_password;
$this->db_name = $db_name;
$this->table = $table;
// Connection @params 'Server', 'Username', 'Password'
$this->connection = mysqli_connect($this->db_server, $this->db_username, $this->db_password, $this->db_name);
// Display Friend Error Message On Connection Failure
if(!$this->connection)
{
die('Could not connect: ' . mysqli_error());
}
// Internal UTF-8
mysqli_query("SET NAMES 'utf8'");
mysqli_query('SET character_set_connection=utf8');
mysqli_query('SET character_set_client=utf8');
mysqli_query('SET character_set_results=utf8');
// Select The Database Name
$db = mysqli_select_db($this->connection, $this->db_name);
// Display Friend Error Message On Database Select Failure
if(!$db)
{
die('Could not select: ' . mysqli_error());
}
$this->result = mysqli_query("SELECT * FROM $this->table ");
}
//////////////////////////
// Results Transformation
/////////////////////////
private function results($result)
{
$result_array = array();
for ($i = 0; $row = mysql_fetch_assoc($result); $i++)
{
$result_array[$i] = $row;
}
return $result_array;
}
/////////////////////
// Time Calcuation
////////////////////
private function time_calculation($timestamp)
{
$period = array(
"second",
"minute",
"hour",
"day",
"week",
"month",
"year",
"decade"
);
$periods = array(
"seconds",
"minutes",
"hours",
"days",
"weeks",
"months",
"years",
"decades"
);
$lengths = array(60,60,24,7,4.35,12,10);
$timenow = date("Y-m-d H:i:s");
$now = strtotime('now');
$difference = $now - $timestamp;
$tense = "ago";
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if ($difference != 1) {
$per = $periods[$j];
} else {
$per = $period[$j];
}
$string_result = $difference . " " . $per . " ago";
return $string_result;
}
//////////////////
// Get Site Title
/////////////////
private function get_title($url)
{
$str = file_get_contents($url);
if(strlen($str) > 0)
{
preg_match("/\<title\>(.*)\<\/title\>/", $str, $title);
return $title[1];
}
}
////////////////////
// Sanitize Integer
///////////////////
public function sanitize_integer($get_id)
{
// clean it
$sanitize = strip_tags($get_id);
$sanitize = str_replace("'","", $sanitize);
$sanitize = str_replace('"', "", $sanitize);
$sanitize = (int) $sanitize;
if(is_int($sanitize))
{
return $sanitize;
}
// return all data before a space
$sanitize = substr($sanitize, 0, strpos($sanitize, ' '));
// get only the numbers
preg_match("/^\d+$/", $sanitize, $matches);
if(!empty($matches['0']))
{
return $matches['0'];
}
}
///////////////////////////
// Get Ids os the messages
//////////////////////////
public function get_messages_id($sender, $channel)
{
// Result Query
$this->result = mysqli_query(
sprintf(
"SELECT id, user_id, channel, storage_a, storage_b FROM $this->table
WHERE channel = %s ",
mysqli_real_escape_string($channel)
)
);
if($this->result)
{
$resultss = $this->results($this->result);
// filter messages based on its storage
foreach($resultss as $res)
{
// get only messages that are not deleted
// just to order data based on logged_in user
if($res['channel'] == $channel )
{
if(
$res['user_id'] == $sender && $res['storage_a'] == 0 ||
$res['user_id'] == $sender && $res['storage_a'] == 0 && $res['storage_b'] == 0 ||
$res['storage_b'] == $res['user_id'] ||
$res['storage_b'] == 0 && $res['storage_b'] == 0
)
{
// kill it
} else {
$results[] = array(
'id' => $res['id'],
'user_id' => $res['user_id'],
'channel' => $res['channel'],
'storage_a' => $res['storage_a'],
'storage_b' => $res['storage_b']
);
}
}
}
if(!empty($results))
{
return $results;
} else {
return false;
}
} else {
return false;
}
}
//////////////////////////////
// Get Server/Client Messages
/////////////////////////////
public function get_messages($message_ID)
{
// Run querys based on weather the client has the message or not
$this->result = mysqli_query(
sprintf(
"SELECT messages FROM $this->table
WHERE id = %s
ORDER BY id",
mysqli_real_escape_string($message_ID))
);
$results = $this->results($this->result);
if($this->result)
{
// Emoticons
$message = str_replace(array_keys($this->emoticons), array_values($this->emoticons), $results['0']['messages']);
return $message;
} else {
return false;
}
}
///////////////
// Get Message
//////////////
public function get_last_message()
{
// Run querys based on weather the client has the message or not
$this->result = mysqli_query(
sprintf(
"SELECT id, messages FROM $this->table
WHERE channel = %s
ORDER BY id DESC LIMIT 1",
mysqli_real_escape_string($this->serverID)
)
);
$result = mysqli_fetch_assoc($this->result);
if($this->result)
{
return $result;
} else {
return false;
}
}
/////////////////////
// Get Messages Time
////////////////////
public function get_messages_time($ID)
{
// Result Query
$this->result = mysqli_query(sprintf("SELECT time FROM $this->table WHERE id = %s", mysqli_real_escape_string($ID)));
$results = mysqli_fetch_assoc($this->result);
if($this->result)
{
return $this->time_calculation($results['time']);
} else {
return false;
}
}
public function get_session_time($serverID)
{
// Result Query
$this->result = mysqli_query(sprintf("SELECT session_time FROM $this->users_table WHERE id = %s AND session = 'offline'", mysqli_real_escape_string($serverID)));
$results = mysqli_fetch_assoc($this->result);
if(mysqli_num_rows($this->result) !== 0)
{
return $this->time_calculation($results['session_time']);
} else {
return false;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get users from users table excluding the logged user because it does not makes sense chatting or messaging to yourself
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function get_users($clientID)
{
// Result Query
$this->result = mysqli_query(sprintf("SELECT $this->users_usernameField, $this->user_idField, status, session FROM $this->users_table WHERE $this->user_idField != %s", mysqli_real_escape_string($clientID)));
if($this->result)
{
return $this->results($this->result);
} else {
return false;
}
}
///////////////////////////////////////
// Get id, username based on a user id
//////////////////////////////////////
public function get_user($serverID, $return)
{
// Result Query
$this->result = mysqli_query(sprintf("SELECT $this->users_usernameField, $this->user_idField FROM $this->users_table WHERE $this->user_idField = %s", mysqli_real_escape_string($serverID)));
if($this->result)
{
$res = mysqli_fetch_assoc($this->result);
switch($return)
{
case "ID":
return $res[$this->user_idField];
break;
case "USERNAME":
return $res[$this->users_usernameField];
break;
}
} else {
return false;
}
}
//////////////////////////////
// find new received messages
/////////////////////////////
public function get_unread_messages($serverID, $clientID)
{
$this->result = mysqli_query(sprintf("SELECT id FROM $this->table WHERE status = '%s' AND user_id = %s AND channel = %s", 'unread', mysqli_real_escape_string($serverID), mysqli_real_escape_string($clientID)));
$result = mysqli_num_rows($this->result);
if($result == 0)
{
return '';
} else {
return mysqli_num_rows($this->result);
}
}
/******************************************************************
* Write Context
*******************************************************************/
////////////////
// Set Messages
///////////////
public function set_message($message)
{
$this->result = mysqli_query(
sprintf("INSERT INTO $this->table
SET
messages = '%s',
time = %s,
user_id = %s,
channel = %s,
storage_a = %s,
storage_b = %s,
status = 'unread'
",
mysqli_real_escape_string(htmlentities($message, ENT_COMPAT, 'UTF-8')),
mysqli_real_escape_string(strtotime('now')),
mysqli_real_escape_string($this->clientID),
mysqli_real_escape_string($this->serverID),
mysqli_real_escape_string($this->clientID),
mysqli_real_escape_string($this->serverID)
)
);
if($this->result)
{
return mysqli_insert_id();
} else {
return false;
}
}
////////////////////////
// Set Messages to read
///////////////////////
public function set_messages_read($serverID)
{
$this->result = mysqli_query(
sprintf("UPDATE $this->table
SET
status = '%s'
WHERE
user_id = '%s' AND status = 'unread'
",
'read',
mysqli_real_escape_string($serverID)
)
);
if($this->result)
{
return true;
} else {
return false;
}
}
///////////////////////////
// Set User Session Status
//////////////////////////
public function set_user_sessionStatus($clientID, $status)
{
switch($status)
{
case "ONLINE":
$this->result = mysqli_query(sprintf("SELECT session FROM $this->users_table WHERE $this->user_idField = '%s'", mysqli_real_escape_string($clientID)));
$is_online = mysqli_fetch_assoc($this->result);
if($is_online['session'] == 'offline') // not online set online
{
$this->result = mysqli_query(
sprintf("UPDATE $this->users_table
SET
session = '%s',
session_time = NOW()
WHERE
$this->user_idField = %s
",
'online',
mysqli_real_escape_string($clientID)
)
);
if($this->result)
{
return true;
} else {
return false;
}
} else {
return false;
}
break;
case "OFFLINE":
$this->result = mysqli_query(
sprintf("UPDATE $this->users_table
SET
session = '%s',
session_time = NOW()
WHERE
$this->user_idField = %s
",
'offline',
mysqli_real_escape_string($clientID)
)
);
if($this->result)
{
return true;
} else {
return false;
}
break;
}
}
//////////////////////
// Unregister Message
/////////////////////
public function unregister_message($message_id, $clientID, $serverID)
{
// Find Owner
$this->result = mysqli_query(
sprintf("SELECT user_id, channel, storage_a, storage_b FROM $this->table
WHERE
id = %s
",
mysqli_real_escape_string($message_id)
)
);
$row = mysqli_fetch_assoc($this->result);
// Delete Magic
if($row['user_id'] == $clientID )
{
if($row['user_id'] == $clientID)
{
$internal_storage_a = 0;
$internal_storage_b = $row['storage_b'];
}
}
// Register Storages (a => client, b => server)
$updated = mysqli_query(
sprintf("UPDATE $this->table
SET
storage_a = %s,
storage_b = %s
WHERE
id = %s
",
mysqli_real_escape_string($internal_storage_a),
mysqli_real_escape_string($internal_storage_b),
mysqli_real_escape_string($message_id)
)
);
if($updated)
{
// check if both client and server does not have the messages to remove them
// If you want to never delete messages remove this code and left just return true;
// Look again
$this->result = mysqli_query(
sprintf("SELECT storage_a, storage_b FROM $this->table
WHERE
id = %s
",
mysqli_real_escape_string($message_id)
)
);
$row = mysqli_fetch_assoc($this->result);
// permanent delete it
if($row['storage_a'] == 0 && $row['storage_b'] == 0)
{
mysqli_query(
sprintf("DELETE FROM $this->table
WHERE
id = %s
",
mysqli_real_escape_string($message_id)
)
);
}
return true;
} else {
return false;
}
}
}
?> | {
"content_hash": "a250d64427fc6b6ae1fd871953c3fdde",
"timestamp": "",
"source": "github",
"line_count": 584,
"max_line_length": 212,
"avg_line_length": 25.125,
"alnum_prop": 0.47168268247802086,
"repo_name": "akashbachhania/jeet99",
"id": "4024e65f1c376c93005baa0495e50f11b68351bf",
"size": "14673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/libraries/jchat/tour_chat/jChat.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "97232"
},
{
"name": "ApacheConf",
"bytes": "3127"
},
{
"name": "Batchfile",
"bytes": "617"
},
{
"name": "C",
"bytes": "192071"
},
{
"name": "CSS",
"bytes": "3061019"
},
{
"name": "CoffeeScript",
"bytes": "15156"
},
{
"name": "HTML",
"bytes": "8639111"
},
{
"name": "JavaScript",
"bytes": "21023736"
},
{
"name": "Makefile",
"bytes": "2043"
},
{
"name": "PHP",
"bytes": "26560466"
}
],
"symlink_target": ""
} |
import useIntlContext from "./use-intl-context";
import { templateReplacement } from "@readerfront/shared/build/template-replacement";
const useIntl = () => {
const { messages: dict = {}, locale } = useIntlContext();
const formatFn = ({ id, defaultMessage, values }) => {
if (dict[id]) {
return values ? templateReplacement(dict[id], values) : dict[id];
}
if (process.env.NODE_ENV === "development") {
console.warn(
`[useIntl] Missing translation for "${id}" in "${locale}" locale.`
);
}
return values
? templateReplacement(defaultMessage, values)
: defaultMessage;
};
return { f: formatFn, locale };
};
export default useIntl;
| {
"content_hash": "aa5c33af6fb2fcde8bfbee29a2f1e832",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 85,
"avg_line_length": 26.923076923076923,
"alnum_prop": 0.6285714285714286,
"repo_name": "dvaJi/ReaderFront",
"id": "29e01a626641ca93df285b854dd6d172b880dae1",
"size": "700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/web/src/hooks/use-intl.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16447"
},
{
"name": "HTML",
"bytes": "23109"
},
{
"name": "JavaScript",
"bytes": "619115"
},
{
"name": "Shell",
"bytes": "1337"
},
{
"name": "TypeScript",
"bytes": "65919"
}
],
"symlink_target": ""
} |
function Templater (template) {
this.template = template;
}
Templater.prototype.compile = function (data) {
var regex = /{{(.*?)}}/g;
var match, loopMatch;
while ((match = regex.exec(this.template))) {
var result = "";
if (!/[!#/]/.test(match[1]))
this.template = this.template.replace(match[0], getProperty(data, match[1]));
else {
if ((loopMatch = /{{!?#(.+?)}}([^]+?){{\/\1}}/g.exec(this.template.substr(regex.lastIndex - match[0].length)))) {
var loopScope = getProperty(data, loopMatch[1]);
if (loopScope && loopScope.forEach) // collection, evaluate sub-template for each
loopScope.forEach(function (element) {
result += new Templater(loopMatch[2]).compile(element);
});
else // conditional
if (/{{!#.*?}}/.test(loopMatch[0])) // scope changer
result = loopScope ? new Templater(loopMatch[2]).compile(getProperty(data, loopMatch[1])) : "";
else // non-scope changer
result = loopScope ? new Templater(loopMatch[2]).compile(data) : "";
this.template = this.template.replace(loopMatch[0], result);
}
else // when this is a broken construct, replace the '{' character with its html escape sequence to break out of the endless loop
this.template = this.template.replace(/{/g, '{');
}
regex.lastIndex -= match[0].length;
}
return this.template;
function getProperty (data, match) {
var parts;
if (/[.]/.test(match)) { // its in a sub object
if (match === ".")
return data;
else {
parts = match.split('.');
return getProperty(data[parts.shift()], parts.join('.'));
}
} else {
parts = match.split(" ");
var topLevel = parts.shift();
return typeof data[topLevel] === "function" ? data[topLevel].apply(data, parts) : data[topLevel];
}
}
}; | {
"content_hash": "15271f3efc5caa7efbf12037d6261be0",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 142,
"avg_line_length": 43.44,
"alnum_prop": 0.5105893186003683,
"repo_name": "kaiyote/templater",
"id": "7bfabc77996c041a63a04e520fb7d936002a1410",
"size": "2172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templater.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2172"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Records Form</title>
</head>
<body>
<form action="pull.php" method="post">
<input type="radio" name="match" value="matched" checked>Matched
<br>
<input type="radio" name="match" value="unmatched">Unmatched
<br/>
<input type="radio" name="match" value="both">Both
<br/>
<input type="submit" value="Get Records">
</form>
</body>
</html>
| {
"content_hash": "d083de15734af2072c27e69b6607c341",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 68,
"avg_line_length": 23.61111111111111,
"alnum_prop": 0.6541176470588236,
"repo_name": "justaniles/ssd-matching",
"id": "e2b0729730b4b0c602653f845e52289f06932a78",
"size": "425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/old/pull.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "23327"
},
{
"name": "HTML",
"bytes": "16956"
},
{
"name": "JavaScript",
"bytes": "36692"
},
{
"name": "PHP",
"bytes": "10664"
},
{
"name": "Shell",
"bytes": "333"
}
],
"symlink_target": ""
} |
// Type definitions for serviceworker-webpack-plugin 1.0
// Project: https://github.com/oliviertassinari/serviceworker-webpack-plugin#readme
// Definitions by: Remco Haszing <https://github.com/remcohaszing>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.7
import { Plugin, Stats } from 'webpack';
declare class ServiceWorkerWebpackPlugin<T = ServiceWorkerWebpackPlugin.ServiceWorkerDefaultOption> extends Plugin {
constructor(options: ServiceWorkerWebpackPlugin.ServiceWorkerWebpackPluginOptions<T>);
}
declare namespace ServiceWorkerWebpackPlugin {
interface ServiceWorkerOption {
assets: string[];
jsonStats?: Stats.ToJsonOutput | undefined;
}
interface ServiceWorkerDefaultOption {
assets: string[];
}
interface ServiceWorkerWebpackPluginOptions<T = ServiceWorkerDefaultOption> {
/**
* Path to the actual service worker implementation.
*/
entry: string;
/**
* Relative (from the webpack's config output.path) output path for emitted script.
*
* @default 'sw.js'
*/
filename?: string | undefined;
/**
* Exclude matched assets from being added to the `serviceWorkerOption.assets` variable. (Blacklist)
*
* @default ['**\/.*', '**\/*.map']
*/
excludes?: string[] | undefined;
/**
* Include matched assets added to the `serviceWorkerOption.assets` variable. (Whitelist)
*
* @default ['**\/*']
*/
includes?: string[] | undefined;
/**
* Specifies the public URL address of the output files when referenced in a browser. We use this value to load the service worker over the network.
*
* @default '/'
*/
publicPath?: string | undefined;
/**
* This callback function can be used to inject statically generated service worker.
*/
template?: ((serviceWorkerOption: T) => Promise<void>) | undefined;
/**
* This callback function receives a raw `serviceWorkerOption` argument. The `jsonStats` key contains all the webpack build information.
*/
transformOptions?: ((serviceWorkerOption: ServiceWorkerOption) => T) | undefined;
/**
* Whether to minimize output.
*
* @default process.env.NODE_ENV === 'production'
*/
minimize?: boolean | undefined;
}
}
export = ServiceWorkerWebpackPlugin;
| {
"content_hash": "deeb64cfc58bcccf22dada6988a96180",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 156,
"avg_line_length": 33.142857142857146,
"alnum_prop": 0.6293103448275862,
"repo_name": "markogresak/DefinitelyTyped",
"id": "83fa7da3eae1be5c3ad491a0a7b183afc6dda8d3",
"size": "2552",
"binary": false,
"copies": "24",
"ref": "refs/heads/master",
"path": "types/serviceworker-webpack-plugin/index.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "17426898"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.functions.utils
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.table.`type`.InternalType
import org.apache.flink.table.`type`.TypeConverters.createInternalTypeFromTypeInfo
import org.apache.flink.table.api.ValidationException
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.functions.AggregateFunction
import org.apache.flink.table.functions.utils.AggSqlFunction.{createOperandTypeChecker, createOperandTypeInference, createReturnTypeInference}
import org.apache.flink.table.functions.utils.UserDefinedFunctionUtils._
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.sql._
import org.apache.calcite.sql.`type`.SqlOperandTypeChecker.Consistency
import org.apache.calcite.sql.`type`._
import org.apache.calcite.sql.parser.SqlParserPos
import org.apache.calcite.sql.validate.SqlUserDefinedAggFunction
import org.apache.calcite.util.Optionality
import java.util
/**
* Calcite wrapper for user-defined aggregate functions.
*
* @param name function name (used by SQL parser)
* @param displayName name to be displayed in operator name
* @param aggregateFunction aggregate function to be called
* @param externalResultType the type information of returned value
* @param externalAccType the type information of the accumulator
* @param typeFactory type factory for converting Flink's between Calcite's types
*/
class AggSqlFunction(
name: String,
displayName: String,
aggregateFunction: AggregateFunction[_, _],
val externalResultType: TypeInformation[_],
val externalAccType: TypeInformation[_],
typeFactory: FlinkTypeFactory,
requiresOver: Boolean)
extends SqlUserDefinedAggFunction(
new SqlIdentifier(name, SqlParserPos.ZERO),
createReturnTypeInference(createInternalTypeFromTypeInfo(externalResultType), typeFactory),
createOperandTypeInference(name, aggregateFunction, typeFactory),
createOperandTypeChecker(name, aggregateFunction),
// Do not need to provide a calcite aggregateFunction here. Flink aggregateion function
// will be generated when translating the calcite relnode to flink runtime execution plan
null,
false,
requiresOver,
Optionality.FORBIDDEN,
typeFactory
) {
def getFunction: AggregateFunction[_, _] = aggregateFunction
override def isDeterministic: Boolean = aggregateFunction.isDeterministic
override def toString: String = displayName
override def getParamTypes: util.List[RelDataType] = null
}
object AggSqlFunction {
def apply(
name: String,
displayName: String,
aggregateFunction: AggregateFunction[_, _],
externalResultType: TypeInformation[_],
externalAccType: TypeInformation[_],
typeFactory: FlinkTypeFactory,
requiresOver: Boolean): AggSqlFunction = {
new AggSqlFunction(
name,
displayName,
aggregateFunction,
externalResultType,
externalAccType,
typeFactory,
requiresOver)
}
private[flink] def createOperandTypeInference(
name: String,
aggregateFunction: AggregateFunction[_, _],
typeFactory: FlinkTypeFactory)
: SqlOperandTypeInference = {
/**
* Operand type inference based on [[AggregateFunction]] given information.
*/
new SqlOperandTypeInference {
override def inferOperandTypes(
callBinding: SqlCallBinding,
returnType: RelDataType,
operandTypes: Array[RelDataType]): Unit = {
val operandTypeInfo = getOperandType(callBinding)
val foundSignature = getAccumulateMethodSignature(aggregateFunction, operandTypeInfo)
.getOrElse(
throw new ValidationException(
s"Given parameters of function '$name' do not match any signature. \n" +
s"Actual: ${signatureInternalToString(operandTypeInfo)} \n" +
s"Expected: ${signaturesToString(aggregateFunction, "accumulate")}"))
val inferredTypes = getParameterTypes(aggregateFunction, foundSignature.drop(1))
.map(typeFactory.createTypeFromInternalType(_, isNullable = true))
for (i <- operandTypes.indices) {
if (i < inferredTypes.length - 1) {
operandTypes(i) = inferredTypes(i)
} else if (null != inferredTypes.last.getComponentType) {
// last argument is a collection, the array type
operandTypes(i) = inferredTypes.last.getComponentType
} else {
operandTypes(i) = inferredTypes.last
}
}
}
}
}
private[flink] def createReturnTypeInference(
resultType: InternalType,
typeFactory: FlinkTypeFactory)
: SqlReturnTypeInference = {
new SqlReturnTypeInference {
override def inferReturnType(opBinding: SqlOperatorBinding): RelDataType = {
typeFactory.createTypeFromInternalType(resultType, isNullable = true)
}
}
}
private[flink] def createOperandTypeChecker(
name: String,
aggregateFunction: AggregateFunction[_, _])
: SqlOperandTypeChecker = {
val methods = checkAndExtractMethods(aggregateFunction, "accumulate")
/**
* Operand type checker based on [[AggregateFunction]] given information.
*/
new SqlOperandTypeChecker {
override def getAllowedSignatures(op: SqlOperator, opName: String): String = {
s"$opName[${signaturesToString(aggregateFunction, "accumulate")}]"
}
override def getOperandCountRange: SqlOperandCountRange = {
var min = 253
var max = -1
var isVarargs = false
methods.foreach( m => {
// do not count accumulator as input
val inputParams = m.getParameterTypes.drop(1)
var len = inputParams.length
if (len > 0 && m.isVarArgs && inputParams(len - 1).isArray) {
isVarargs = true
len = len - 1
}
max = Math.max(len, max)
min = Math.min(len, min)
})
if (isVarargs) {
// if eval method is varargs, set max to -1 to skip length check in Calcite
max = -1
}
SqlOperandCountRanges.between(min, max)
}
override def checkOperandTypes(
callBinding: SqlCallBinding,
throwOnFailure: Boolean)
: Boolean = {
val operandTypeInfo = getOperandType(callBinding)
val foundSignature = getAccumulateMethodSignature(aggregateFunction, operandTypeInfo)
if (foundSignature.isEmpty) {
if (throwOnFailure) {
throw new ValidationException(
s"Given parameters of function '$name' do not match any signature. \n" +
s"Actual: ${signatureInternalToString(operandTypeInfo)} \n" +
s"Expected: ${signaturesToString(aggregateFunction, "accumulate")}")
} else {
false
}
} else {
true
}
}
override def isOptional(i: Int): Boolean = false
override def getConsistency: Consistency = Consistency.NONE
}
}
}
| {
"content_hash": "1db65b856cfcd0133ef57d6f9dae102d",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 142,
"avg_line_length": 35.03921568627451,
"alnum_prop": 0.6838276440962507,
"repo_name": "ueshin/apache-flink",
"id": "c3c33203c6fb142da2a158556c59d618230546f8",
"size": "7953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/functions/utils/AggSqlFunction.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5667"
},
{
"name": "CSS",
"bytes": "18100"
},
{
"name": "Clojure",
"bytes": "88796"
},
{
"name": "CoffeeScript",
"bytes": "91220"
},
{
"name": "Dockerfile",
"bytes": "9788"
},
{
"name": "HTML",
"bytes": "86821"
},
{
"name": "Java",
"bytes": "42052018"
},
{
"name": "JavaScript",
"bytes": "8267"
},
{
"name": "Python",
"bytes": "249644"
},
{
"name": "Scala",
"bytes": "8365242"
},
{
"name": "Shell",
"bytes": "398033"
}
],
"symlink_target": ""
} |
#include "TinyDebugSerial.h"
TinyDebugSerialWriter_38400 tdsw38400;
| {
"content_hash": "35424cf30a4dce0612b532273d864243",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 38,
"avg_line_length": 15.2,
"alnum_prop": 0.7631578947368421,
"repo_name": "sdvornikov/avr-stuff",
"id": "5c68c31ebb300303c131e2270b0736704e107aa1",
"size": "1052",
"binary": false,
"copies": "36",
"ref": "refs/heads/master",
"path": "hardware/tiny/avr/cores/tiny/TinyDebugSerial38400.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "7740"
},
{
"name": "C",
"bytes": "117299"
},
{
"name": "C++",
"bytes": "125945"
},
{
"name": "Perl",
"bytes": "3183"
},
{
"name": "Processing",
"bytes": "5339"
}
],
"symlink_target": ""
} |
package systemd
import (
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
systemd1 "github.com/coreos/go-systemd/dbus"
"github.com/dotcloud/docker/pkg/cgroups"
"github.com/dotcloud/docker/pkg/systemd"
"github.com/godbus/dbus"
)
type systemdCgroup struct {
cleanupDirs []string
}
type DeviceAllow struct {
Node string
Permissions string
}
var (
connLock sync.Mutex
theConn *systemd1.Conn
hasStartTransientUnit bool
)
func UseSystemd() bool {
if !systemd.SdBooted() {
return false
}
connLock.Lock()
defer connLock.Unlock()
if theConn == nil {
var err error
theConn, err = systemd1.New()
if err != nil {
return false
}
// Assume we have StartTransientUnit
hasStartTransientUnit = true
// But if we get UnknownMethod error we don't
if _, err := theConn.StartTransientUnit("test.scope", "invalid"); err != nil {
if dbusError, ok := err.(dbus.Error); ok {
if dbusError.Name == "org.freedesktop.DBus.Error.UnknownMethod" {
hasStartTransientUnit = false
}
}
}
}
return hasStartTransientUnit
}
func getIfaceForUnit(unitName string) string {
if strings.HasSuffix(unitName, ".scope") {
return "Scope"
}
if strings.HasSuffix(unitName, ".service") {
return "Service"
}
return "Unit"
}
type cgroupArg struct {
File string
Value string
}
func Apply(c *cgroups.Cgroup, pid int) (cgroups.ActiveCgroup, error) {
var (
unitName = c.Parent + "-" + c.Name + ".scope"
slice = "system.slice"
properties []systemd1.Property
cpuArgs []cgroupArg
cpusetArgs []cgroupArg
memoryArgs []cgroupArg
res systemdCgroup
)
// First set up things not supported by systemd
// -1 disables memorySwap
if c.MemorySwap >= 0 && (c.Memory != 0 || c.MemorySwap > 0) {
memorySwap := c.MemorySwap
if memorySwap == 0 {
// By default, MemorySwap is set to twice the size of RAM.
memorySwap = c.Memory * 2
}
memoryArgs = append(memoryArgs, cgroupArg{"memory.memsw.limit_in_bytes", strconv.FormatInt(memorySwap, 10)})
}
if c.CpusetCpus != "" {
cpusetArgs = append(cpusetArgs, cgroupArg{"cpuset.cpus", c.CpusetCpus})
}
if c.Slice != "" {
slice = c.Slice
}
properties = append(properties,
systemd1.Property{"Slice", dbus.MakeVariant(slice)},
systemd1.Property{"Description", dbus.MakeVariant("docker container " + c.Name)},
systemd1.Property{"PIDs", dbus.MakeVariant([]uint32{uint32(pid)})},
)
if !c.DeviceAccess {
properties = append(properties,
systemd1.Property{"DevicePolicy", dbus.MakeVariant("strict")},
systemd1.Property{"DeviceAllow", dbus.MakeVariant([]DeviceAllow{
{"/dev/null", "rwm"},
{"/dev/zero", "rwm"},
{"/dev/full", "rwm"},
{"/dev/random", "rwm"},
{"/dev/urandom", "rwm"},
{"/dev/tty", "rwm"},
{"/dev/console", "rwm"},
{"/dev/tty0", "rwm"},
{"/dev/tty1", "rwm"},
{"/dev/pts/ptmx", "rwm"},
// There is no way to add /dev/pts/* here atm, so we hack this manually below
// /dev/pts/* (how to add this?)
// Same with tuntap, which doesn't exist as a node most of the time
})})
}
// Always enable accounting, this gets us the same behaviour as the fs implementation,
// plus the kernel has some problems with joining the memory cgroup at a later time.
properties = append(properties,
systemd1.Property{"MemoryAccounting", dbus.MakeVariant(true)},
systemd1.Property{"CPUAccounting", dbus.MakeVariant(true)},
systemd1.Property{"BlockIOAccounting", dbus.MakeVariant(true)})
if c.Memory != 0 {
properties = append(properties,
systemd1.Property{"MemoryLimit", dbus.MakeVariant(uint64(c.Memory))})
}
// TODO: MemoryReservation and MemorySwap not available in systemd
if c.CpuShares != 0 {
properties = append(properties,
systemd1.Property{"CPUShares", dbus.MakeVariant(uint64(c.CpuShares))})
}
if _, err := theConn.StartTransientUnit(unitName, "replace", properties...); err != nil {
return nil, err
}
// To work around the lack of /dev/pts/* support above we need to manually add these
// so, ask systemd for the cgroup used
props, err := theConn.GetUnitTypeProperties(unitName, getIfaceForUnit(unitName))
if err != nil {
return nil, err
}
cgroup := props["ControlGroup"].(string)
if !c.DeviceAccess {
mountpoint, err := cgroups.FindCgroupMountpoint("devices")
if err != nil {
return nil, err
}
path := filepath.Join(mountpoint, cgroup)
// /dev/pts/*
if err := ioutil.WriteFile(filepath.Join(path, "devices.allow"), []byte("c 136:* rwm"), 0700); err != nil {
return nil, err
}
// tuntap
if err := ioutil.WriteFile(filepath.Join(path, "devices.allow"), []byte("c 10:200 rwm"), 0700); err != nil {
return nil, err
}
}
if len(cpuArgs) != 0 {
mountpoint, err := cgroups.FindCgroupMountpoint("cpu")
if err != nil {
return nil, err
}
path := filepath.Join(mountpoint, cgroup)
for _, arg := range cpuArgs {
if err := ioutil.WriteFile(filepath.Join(path, arg.File), []byte(arg.Value), 0700); err != nil {
return nil, err
}
}
}
if len(memoryArgs) != 0 {
mountpoint, err := cgroups.FindCgroupMountpoint("memory")
if err != nil {
return nil, err
}
path := filepath.Join(mountpoint, cgroup)
for _, arg := range memoryArgs {
if err := ioutil.WriteFile(filepath.Join(path, arg.File), []byte(arg.Value), 0700); err != nil {
return nil, err
}
}
}
if len(cpusetArgs) != 0 {
// systemd does not atm set up the cpuset controller, so we must manually
// join it. Additionally that is a very finicky controller where each
// level must have a full setup as the default for a new directory is "no cpus",
// so we avoid using any hierarchies here, creating a toplevel directory.
mountpoint, err := cgroups.FindCgroupMountpoint("cpuset")
if err != nil {
return nil, err
}
initPath, err := cgroups.GetInitCgroupDir("cpuset")
if err != nil {
return nil, err
}
rootPath := filepath.Join(mountpoint, initPath)
path := filepath.Join(mountpoint, initPath, c.Parent+"-"+c.Name)
res.cleanupDirs = append(res.cleanupDirs, path)
if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
return nil, err
}
foundCpus := false
foundMems := false
for _, arg := range cpusetArgs {
if arg.File == "cpuset.cpus" {
foundCpus = true
}
if arg.File == "cpuset.mems" {
foundMems = true
}
if err := ioutil.WriteFile(filepath.Join(path, arg.File), []byte(arg.Value), 0700); err != nil {
return nil, err
}
}
// These are required, if not specified inherit from parent
if !foundCpus {
s, err := ioutil.ReadFile(filepath.Join(rootPath, "cpuset.cpus"))
if err != nil {
return nil, err
}
if err := ioutil.WriteFile(filepath.Join(path, "cpuset.cpus"), s, 0700); err != nil {
return nil, err
}
}
// These are required, if not specified inherit from parent
if !foundMems {
s, err := ioutil.ReadFile(filepath.Join(rootPath, "cpuset.mems"))
if err != nil {
return nil, err
}
if err := ioutil.WriteFile(filepath.Join(path, "cpuset.mems"), s, 0700); err != nil {
return nil, err
}
}
if err := ioutil.WriteFile(filepath.Join(path, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0700); err != nil {
return nil, err
}
}
return &res, nil
}
func (c *systemdCgroup) Cleanup() error {
// systemd cleans up, we don't need to do much
for _, path := range c.cleanupDirs {
os.RemoveAll(path)
}
return nil
}
| {
"content_hash": "03f491cd4fe7a05b58eeef5824746b71",
"timestamp": "",
"source": "github",
"line_count": 294,
"max_line_length": 112,
"avg_line_length": 25.421768707482993,
"alnum_prop": 0.656007492641156,
"repo_name": "tutumcloud/docker",
"id": "c4b0937b63e6fe5d1f77e4ff40ff01b00764a622",
"size": "7491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/cgroups/systemd/apply_systemd.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18491"
},
{
"name": "Go",
"bytes": "1485310"
},
{
"name": "JavaScript",
"bytes": "21127"
},
{
"name": "Perl",
"bytes": "2199"
},
{
"name": "Shell",
"bytes": "114121"
},
{
"name": "VimL",
"bytes": "671"
}
],
"symlink_target": ""
} |
module.exports = function(context) {
context.test_string = 'Solidus';
return context;
}; | {
"content_hash": "a8e6216fd72677c1fc0f9fe725cffb92",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 36,
"avg_line_length": 23,
"alnum_prop": 0.7065217391304348,
"repo_name": "solidusjs/solidus",
"id": "7afe336ef3b7aa05ad5341e19b8039f48527643f",
"size": "92",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/fixtures/site 1/preprocessors/helpers.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "104095"
}
],
"symlink_target": ""
} |
#ifndef PPAPI_C_PPB_VAR_H_
#define PPAPI_C_PPB_VAR_H_
#include "ppapi/c/pp_bool.h"
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_macros.h"
#include "ppapi/c/pp_module.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/pp_stdint.h"
#include "ppapi/c/pp_var.h"
#define PPB_VAR_INTERFACE "PPB_Var;0.5"
/**
* @file
* This file defines the PPB_Var struct.
*/
/**
* @addtogroup Interfaces
* @{
*/
/**
* PPB_Var API
*/
struct PPB_Var {
/**
* Adds a reference to the given var. If this is not a refcounted object,
* this function will do nothing so you can always call it no matter what the
* type.
*/
void (*AddRef)(struct PP_Var var);
/**
* Removes a reference to given var, deleting it if the internal refcount
* becomes 0. If the given var is not a refcounted object, this function will
* do nothing so you can always call it no matter what the type.
*/
void (*Release)(struct PP_Var var);
/**
* Creates a string var from a string. The string must be encoded in valid
* UTF-8 and is NOT NULL-terminated, the length must be specified in |len|.
* It is an error if the string is not valid UTF-8.
*
* If the length is 0, the |data| pointer will not be dereferenced and may
* be NULL. Note, however, that if you do this, the "NULL-ness" will not be
* preserved, as VarToUtf8 will never return NULL on success, even for empty
* strings.
*
* The resulting object will be a refcounted string object. It will be
* AddRef()ed for the caller. When the caller is done with it, it should be
* Release()d.
*
* On error (basically out of memory to allocate the string, or input that
* is not valid UTF-8), this function will return a Null var.
*/
struct PP_Var (*VarFromUtf8)(PP_Module module,
const char* data, uint32_t len);
/**
* Converts a string-type var to a char* encoded in UTF-8. This string is NOT
* NULL-terminated. The length will be placed in |*len|. If the string is
* valid but empty the return value will be non-NULL, but |*len| will still
* be 0.
*
* If the var is not a string, this function will return NULL and |*len| will
* be 0.
*
* The returned buffer will be valid as long as the underlying var is alive.
* If the plugin frees its reference, the string will be freed and the pointer
* will be to random memory.
*/
const char* (*VarToUtf8)(struct PP_Var var, uint32_t* len);
};
/**
* @}
*/
#endif /* PPAPI_C_PPB_VAR_H_ */
| {
"content_hash": "abccae234b3c84d6795bbcef2f125110",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 80,
"avg_line_length": 30.301204819277107,
"alnum_prop": 0.658051689860835,
"repo_name": "wistoch/meego-app-browser",
"id": "56280b3c659e5dd57773447f0d6d2d68bafa6915",
"size": "2687",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ppapi/c/ppb_var.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6772"
},
{
"name": "Assembly",
"bytes": "1123040"
},
{
"name": "Awk",
"bytes": "9422"
},
{
"name": "C",
"bytes": "68482407"
},
{
"name": "C++",
"bytes": "95729434"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Go",
"bytes": "3744"
},
{
"name": "Java",
"bytes": "11354"
},
{
"name": "JavaScript",
"bytes": "5466857"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5292"
},
{
"name": "Objective-C",
"bytes": "4890308"
},
{
"name": "PHP",
"bytes": "97796"
},
{
"name": "Perl",
"bytes": "521006"
},
{
"name": "Prolog",
"bytes": "435"
},
{
"name": "Python",
"bytes": "4833145"
},
{
"name": "Shell",
"bytes": "1346070"
},
{
"name": "Tcl",
"bytes": "200213"
},
{
"name": "XML",
"bytes": "13001"
}
],
"symlink_target": ""
} |
angular.module("plantApp")
.directive("settree", function() {
return {
restrict: "E",
templateUrl: 'partials/treesetting.html',
controller: 'settreeCtrl',
scope: {}
};
}); | {
"content_hash": "4a4cff1072f1f990b8a68eb46b98c6d4",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 43,
"avg_line_length": 20.666666666666668,
"alnum_prop": 0.6451612903225806,
"repo_name": "BonesAndTeeth/EPlant",
"id": "0c2696e96efc484452639fd21d71421202a9bc77",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/directives/settree.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "784"
},
{
"name": "JavaScript",
"bytes": "1222283"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83_goodG2B.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-83_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using malloc() and set data pointer to a small buffer
* GoodSource: Allocate using malloc() and set data pointer to a large buffer
* Sinks: memcpy
* BadSink : Copy int64_t array to data using memcpy
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83.h"
namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83
{
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83_goodG2B::CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83_goodG2B(int64_t * dataCopy)
{
data = dataCopy;
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (int64_t *)malloc(100*sizeof(int64_t));
}
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83_goodG2B::~CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83_goodG2B()
{
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
}
#endif /* OMITGOOD */
| {
"content_hash": "12109744575cea5000c5c50ce6d22992",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 160,
"avg_line_length": 40.829268292682926,
"alnum_prop": 0.6989247311827957,
"repo_name": "maurer/tiamat",
"id": "b800ad20c65596a966e761eb679d6bd48dbcae72",
"size": "1674",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_83_goodG2B.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.spongepowered.common.mixin.api.mcp.entity.item;
import net.minecraft.entity.item.EntityBoat;
import org.spongepowered.api.data.manipulator.DataManipulator;
import org.spongepowered.api.data.type.TreeTypes;
import org.spongepowered.api.entity.vehicle.Boat;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.data.manipulator.mutable.block.SpongeTreeData;
import org.spongepowered.common.mixin.api.mcp.entity.EntityMixin_API;
import java.util.Collection;
// TODO 1.9: Refactor this for boat overhaul
@Mixin(EntityBoat.class)
@Implements(@Interface(iface = Boat.class, prefix = "apiBoat$"))
public abstract class EntityBoatMixin_API extends EntityMixin_API implements Boat {
@Shadow public abstract EntityBoat.Type getBoatType();
private double maxSpeed = 0.35D;
private boolean moveOnLand = false;
private double occupiedDecelerationSpeed = 0D;
private double unoccupiedDecelerationSpeed = 0.8D;
@Override
protected void spongeApi$supplyVanillaManipulators(final Collection<? super DataManipulator<?, ?>> manipulators) {
super.spongeApi$supplyVanillaManipulators(manipulators);
final EntityBoat.Type boatType = this.getBoatType();
if (boatType == EntityBoat.Type.OAK) {
manipulators.add(new SpongeTreeData(TreeTypes.OAK));
} else if ( boatType == EntityBoat.Type.BIRCH) {
manipulators.add(new SpongeTreeData(TreeTypes.BIRCH));
} else if ( boatType == EntityBoat.Type.JUNGLE) {
manipulators.add(new SpongeTreeData(TreeTypes.JUNGLE));
} else if ( boatType == EntityBoat.Type.DARK_OAK) {
manipulators.add(new SpongeTreeData(TreeTypes.DARK_OAK));
} else if ( boatType == EntityBoat.Type.ACACIA) {
manipulators.add(new SpongeTreeData(TreeTypes.ACACIA));
} else if ( boatType == EntityBoat.Type.SPRUCE) {
manipulators.add(new SpongeTreeData(TreeTypes.SPRUCE));
}
}
@Intrinsic
public boolean apiBoat$isInWater() {
return !this.onGround;
}
@Override
public double getMaxSpeed() {
return this.maxSpeed;
}
@Override
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = maxSpeed;
}
@Override
public boolean canMoveOnLand() {
return this.moveOnLand;
}
@Override
public void setMoveOnLand(boolean moveOnLand) {
this.moveOnLand = moveOnLand;
}
@Override
public double getOccupiedDeceleration() {
return this.occupiedDecelerationSpeed;
}
@Override
public void setOccupiedDeceleration(double occupiedDeceleration) {
this.occupiedDecelerationSpeed = occupiedDeceleration;
}
@Override
public double getUnoccupiedDeceleration() {
return this.unoccupiedDecelerationSpeed;
}
@Override
public void setUnoccupiedDeceleration(double unoccupiedDeceleration) {
this.unoccupiedDecelerationSpeed = unoccupiedDeceleration;
}
}
| {
"content_hash": "29a2fc1a5151120efc4fc3484de53404",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 118,
"avg_line_length": 33.95744680851064,
"alnum_prop": 0.7161654135338346,
"repo_name": "SpongePowered/SpongeCommon",
"id": "8d2d450d14f8718b188d5f70a1851ec3d9b881ac",
"size": "4439",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable-7",
"path": "src/main/java/org/spongepowered/common/mixin/api/mcp/entity/item/EntityBoatMixin_API.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "14153592"
},
{
"name": "Shell",
"bytes": "1072"
}
],
"symlink_target": ""
} |
var expectedVolume1 = {
volumeId: 'removable:mount_path1',
mountPath: '/removable/mount_path1',
sourcePath: 'device_path1',
volumeType: 'removable',
deviceType: 'usb',
devicePath: 'system_path_prefix1',
deviceLabel: 'drive_label1',
isParentDevice: false,
isReadOnly: false,
profile: {profileId: "", displayName: "", isCurrentProfile: true}
};
var expectedVolume2 = {
volumeId: 'removable:mount_path2',
mountPath: '/removable/mount_path2',
sourcePath: 'device_path2',
volumeType: 'removable',
deviceType: 'mobile',
devicePath: 'system_path_prefix2',
deviceLabel: 'drive_label2',
isParentDevice: true,
isReadOnly: true,
profile: {profileId: "", displayName: "", isCurrentProfile: true}
};
var expectedVolume3 = {
volumeId: 'removable:mount_path3',
mountPath: '/removable/mount_path3',
sourcePath: 'device_path3',
volumeType: 'removable',
deviceType: 'optical',
devicePath: 'system_path_prefix3',
deviceLabel: 'drive_label3',
isParentDevice: true,
isReadOnly: false,
profile: {profileId: "", displayName: "", isCurrentProfile: true}
};
var expectedDownloadsVolume = {
volumeId: /^downloads:Downloads[^\/]*$/,
mountPath: /^\/Downloads[^\/]*$/,
volumeType: 'downloads',
isReadOnly: false,
profile: {profileId: "", displayName: "", isCurrentProfile: true}
};
var expectedDriveVolume = {
volumeId: /^drive:drive[^\/]*$/,
mountPath: /^\/drive[^\/]*$/,
sourcePath: /^\/special\/drive[^\/]*$/,
volumeType: 'drive',
isReadOnly: false,
profile: {profileId: "", displayName: "", isCurrentProfile: true}
};
var expectedArchiveVolume = {
volumeId: 'archive:archive_mount_path',
mountPath: '/archive/archive_mount_path',
sourcePath: /removable\/mount_path3\/archive.zip$/,
volumeType: 'archive',
isReadOnly: true,
profile: {profileId: "", displayName: "", isCurrentProfile: true}
};
// List of expected mount points.
// NOTE: this has to be synced with values in file_browser_private_apitest.cc
// and values sorted by volumeId.
var expectedVolumeList = [
expectedArchiveVolume,
expectedDownloadsVolume,
expectedDriveVolume,
expectedVolume1,
expectedVolume2,
expectedVolume3,
];
function validateObject(received, expected, name) {
for (var key in expected) {
if (expected[key] instanceof RegExp) {
if (!expected[key].test(received[key])) {
console.warn('Expected "' + key + '" ' + name + ' property to match: ' +
expected[key] + ', but got: "' + received[key] + '".');
return false;
}
} else if (expected[key] instanceof Object) {
if (!validateObject(received[key], expected[key], name + "." + key))
return false;
} else if (received[key] != expected[key]) {
console.warn('Expected "' + key + '" ' + name + ' property to be: "' +
expected[key] + '"' + ', but got: "' + received[key] +
'" instead.');
return false;
}
}
var expectedKeys = Object.keys(expected);
var receivedKeys = Object.keys(received);
if (expectedKeys.length !== receivedKeys.length) {
var unexpectedKeys = [];
for (var i = 0; i < receivedKeys.length; i++) {
if (!(receivedKeys[i] in expected))
unexpectedKeys.push(receivedKeys[i]);
}
console.warn('Unexpected properties found: ' + unexpectedKeys);
return false;
}
return true;
}
chrome.test.runTests([
function removeMount() {
chrome.fileBrowserPrivate.removeMount('archive:archive_mount_path');
// We actually check this one on C++ side. If MountLibrary.RemoveMount
// doesn't get called, test will fail.
chrome.test.succeed();
},
function getVolumeMetadataList() {
chrome.fileBrowserPrivate.getVolumeMetadataList(
chrome.test.callbackPass(function(result) {
chrome.test.assertEq(expectedVolumeList.length, result.length,
'getMountPoints returned wrong number of mount points.');
for (var i = 0; i < expectedVolumeList.length; i++) {
chrome.test.assertTrue(
validateObject(
result[i], expectedVolumeList[i], 'volumeMetadata'),
'getMountPoints result[' + i + '] not as expected');
}
}));
}
]);
| {
"content_hash": "fd700b00ee09db296ce32ff43e419137",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 80,
"avg_line_length": 31.66417910447761,
"alnum_prop": 0.6455338204100872,
"repo_name": "ChromiumWebApps/chromium",
"id": "5627b87271cff055a70c360c8d4c4e7d8bd7fd42",
"size": "4477",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/test/data/extensions/api_test/file_browser/mount_test/test.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "52960"
},
{
"name": "Awk",
"bytes": "8660"
},
{
"name": "C",
"bytes": "42286199"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "198616766"
},
{
"name": "CSS",
"bytes": "937333"
},
{
"name": "DOT",
"bytes": "2984"
},
{
"name": "Java",
"bytes": "5695686"
},
{
"name": "JavaScript",
"bytes": "21967126"
},
{
"name": "M",
"bytes": "2190"
},
{
"name": "Matlab",
"bytes": "2262"
},
{
"name": "Objective-C",
"bytes": "7602057"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "1210885"
},
{
"name": "Python",
"bytes": "10774996"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Shell",
"bytes": "1316721"
},
{
"name": "Tcl",
"bytes": "277091"
},
{
"name": "TypeScript",
"bytes": "1560024"
},
{
"name": "XSLT",
"bytes": "13493"
},
{
"name": "nesC",
"bytes": "15243"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "8b46c079852d6ce6b056a1dfc000bafe",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.7218045112781954,
"repo_name": "mdoering/backbone",
"id": "4f57ca65d4dacfc7bfb656a1b87475b8085f4ec9",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lupinus/Lupinus argenteus/Lupinus argenteus argenteus/ Syn. Lupinus cariciformes/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>flocq-quickchick: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1+2 / flocq-quickchick - 1.0.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
flocq-quickchick
<small>
1.0.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-10 09:25:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-10 09:25:57 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1+2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
name: "coq-flocq-quickchick"
version: "1.0.0"
synopsis: "Flocq binary_float generators for QuickChick testing framework"
maintainer: "Yaroslav Kogevnikov <[email protected]>"
authors: "Yaroslav Kogevnikov <[email protected]>"
license: "MIT"
homepage: "https://github.com/digamma-ai/flocq-quickchick"
bug-reports: "https://github.com/digamma-ai/flocq-quickchick/issues"
depends: [
"coq" {= "8.8.2"}
"coq-quickchick" {>= "1.0.2"}
"coq-flocq" {= "3.1.0"}
]
build: [
["coq_makefile" "-f" "_CoqProject" "-o" "Makefile"]
[make]
]
install: [make "install"]
dev-repo: "git+https://github.com/digamma-ai/flocq-quickchick.git"
url {
src: "https://github.com/digamma-ai/flocq-quickchick/archive/1.0.0.tar.gz"
checksum: "md5=54ce38b1aa1bfbb9dc52709e2be0eb8f"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-flocq-quickchick.1.0.0 coq.8.7.1+2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2).
The following dependencies couldn't be met:
- coq-flocq-quickchick -> coq-quickchick >= 1.0.2 -> ocaml >= 4.04.0
base of this switch (use `--unlock-base' to force)
- coq-flocq-quickchick -> coq-quickchick >= 1.0.2 -> coq >= 8.10 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-flocq-quickchick.1.0.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "a2ae0b68ea1e6df48e5a46f9ca798a6d",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 159,
"avg_line_length": 42.42261904761905,
"alnum_prop": 0.5432860951311912,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "2e5c0a60a7133d655fbf1d753caec9220e29bbe6",
"size": "7152",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.7.1+2/flocq-quickchick/1.0.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import React, {PureComponent, ChangeEvent} from 'react'
import {withRouter, WithRouterProps} from 'react-router'
import {connect} from 'react-redux'
// Components
import {Overlay} from '@influxdata/clockface'
import BucketOverlayForm from 'src/buckets/components/BucketOverlayForm'
// Actions
import {updateBucket} from 'src/buckets/actions'
// Constants
import {DEFAULT_SECONDS} from 'src/buckets/components/Retention'
// Types
import {AppState, Bucket} from 'src/types'
interface State {
bucket: Bucket
ruleType: 'expire'
}
interface StateProps {
bucket: Bucket
}
interface DispatchProps {
onUpdateBucket: typeof updateBucket
}
type Props = StateProps & DispatchProps & WithRouterProps
class UpdateBucketOverlay extends PureComponent<Props, State> {
constructor(props) {
super(props)
const {bucket} = this.props
this.state = {
ruleType: this.ruleType(bucket),
bucket,
}
}
public render() {
const {bucket, ruleType} = this.state
return (
<Overlay visible={true}>
<Overlay.Container maxWidth={500}>
<Overlay.Header title="Edit Bucket" onDismiss={this.handleClose} />
<Overlay.Body>
<BucketOverlayForm
name={bucket.name}
buttonText="Save Changes"
ruleType={ruleType}
onCloseModal={this.handleClose}
onSubmit={this.handleSubmit}
disableRenaming={true}
onChangeInput={this.handleChangeInput}
retentionSeconds={this.retentionSeconds}
onChangeRuleType={this.handleChangeRuleType}
onChangeRetentionRule={this.handleChangeRetentionRule}
/>
</Overlay.Body>
</Overlay.Container>
</Overlay>
)
}
private get retentionSeconds(): number {
const rule = this.state.bucket.retentionRules.find(r => r.type === 'expire')
if (!rule) {
return DEFAULT_SECONDS
}
return rule.everySeconds
}
private ruleType = (bucket: Bucket): 'expire' => {
const rule = bucket.retentionRules.find(r => r.type === 'expire')
if (!rule) {
return null
}
return 'expire'
}
private handleChangeRetentionRule = (everySeconds: number): void => {
const bucket = {
...this.state.bucket,
retentionRules: [{type: 'expire' as 'expire', everySeconds}],
}
this.setState({bucket})
}
private handleChangeRuleType = (ruleType: 'expire') => {
this.setState({ruleType})
}
private handleSubmit = (e): void => {
e.preventDefault()
const {onUpdateBucket} = this.props
const {ruleType, bucket} = this.state
if (ruleType === null) {
onUpdateBucket({...bucket, retentionRules: []})
this.handleClose()
return
}
onUpdateBucket(bucket)
this.handleClose()
}
private handleChangeInput = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
const key = e.target.name
const bucket = {...this.state.bucket, [key]: value}
this.setState({bucket})
}
private handleClose = () => {
const {orgID} = this.props.params
this.props.router.push(`/orgs/${orgID}/load-data/buckets`)
}
}
const mstp = ({buckets}: AppState, props: Props): StateProps => {
const {
params: {bucketID},
} = props
const bucket = buckets.list.find(b => b.id === bucketID)
return {
bucket,
}
}
const mdtp: DispatchProps = {
onUpdateBucket: updateBucket,
}
export default connect<StateProps, DispatchProps, {}>(
mstp,
mdtp
)(withRouter(UpdateBucketOverlay))
| {
"content_hash": "e26d04b52d9e18b0516ed3bd223b0385",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 80,
"avg_line_length": 23.473684210526315,
"alnum_prop": 0.6418161434977578,
"repo_name": "mark-rushakoff/influxdb",
"id": "3b6c427e4c423d2d78f45bffd19504662ace579e",
"size": "3581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ui/src/buckets/components/UpdateBucketOverlay.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "201052"
},
{
"name": "Dockerfile",
"bytes": "520"
},
{
"name": "Go",
"bytes": "8495025"
},
{
"name": "HTML",
"bytes": "727"
},
{
"name": "JavaScript",
"bytes": "3213"
},
{
"name": "Makefile",
"bytes": "13478"
},
{
"name": "Python",
"bytes": "42767"
},
{
"name": "Shell",
"bytes": "16825"
},
{
"name": "TypeScript",
"bytes": "2593815"
}
],
"symlink_target": ""
} |
"""generated automatically by auto_dao.py"""
from __future__ import division
from sql_dao import SQLDAO
from vistrails.db.versions.v0_9_4.domain import *
class DBPortSpecSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'port_spec'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'name', 'type', 'spec', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'port_spec'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
name = self.convertFromDB(row[1], 'str', 'varchar(22)')
type = self.convertFromDB(row[2], 'str', 'varchar(255)')
spec = self.convertFromDB(row[3], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[4], 'str', 'char(16)')
entity_id = self.convertFromDB(row[5], 'long', 'int')
entity_type = self.convertFromDB(row[6], 'str', 'char(16)')
parent = self.convertFromDB(row[7], 'long', 'long')
portSpec = DBPortSpec(name=name,
type=type,
spec=spec,
id=id)
portSpec.db_parentType = parentType
portSpec.db_entity_id = entity_id
portSpec.db_entity_type = entity_type
portSpec.db_parent = parent
portSpec.is_dirty = False
res[('portSpec', id)] = portSpec
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'module':
p = all_objects[('module', obj.db_parent)]
p.db_add_portSpec(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'name', 'type', 'spec', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'port_spec'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(22)')
if hasattr(obj, 'db_type') and obj.db_type is not None:
columnMap['type'] = \
self.convertToDB(obj.db_type, 'str', 'varchar(255)')
if hasattr(obj, 'db_spec') and obj.db_spec is not None:
columnMap['spec'] = \
self.convertToDB(obj.db_spec, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'port_spec'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBModuleSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'module'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'cache', 'name', 'namespace', 'package', 'version', 'tag', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'module'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
cache = self.convertFromDB(row[1], 'int', 'int')
name = self.convertFromDB(row[2], 'str', 'varchar(255)')
namespace = self.convertFromDB(row[3], 'str', 'varchar(255)')
package = self.convertFromDB(row[4], 'str', 'varchar(511)')
version = self.convertFromDB(row[5], 'str', 'varchar(255)')
tag = self.convertFromDB(row[6], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[7], 'str', 'char(16)')
entity_id = self.convertFromDB(row[8], 'long', 'int')
entity_type = self.convertFromDB(row[9], 'str', 'char(16)')
parent = self.convertFromDB(row[10], 'long', 'long')
module = DBModule(cache=cache,
name=name,
namespace=namespace,
package=package,
version=version,
tag=tag,
id=id)
module.db_parentType = parentType
module.db_entity_id = entity_id
module.db_entity_type = entity_type
module.db_parent = parent
module.is_dirty = False
res[('module', id)] = module
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_module(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'cache', 'name', 'namespace', 'package', 'version', 'tag', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'module'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_cache') and obj.db_cache is not None:
columnMap['cache'] = \
self.convertToDB(obj.db_cache, 'int', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_namespace') and obj.db_namespace is not None:
columnMap['namespace'] = \
self.convertToDB(obj.db_namespace, 'str', 'varchar(255)')
if hasattr(obj, 'db_package') and obj.db_package is not None:
columnMap['package'] = \
self.convertToDB(obj.db_package, 'str', 'varchar(511)')
if hasattr(obj, 'db_version') and obj.db_version is not None:
columnMap['version'] = \
self.convertToDB(obj.db_version, 'str', 'varchar(255)')
if hasattr(obj, 'db_tag') and obj.db_tag is not None:
columnMap['tag'] = \
self.convertToDB(obj.db_tag, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
if obj.db_location is not None:
child = obj.db_location
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_functions:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_portSpecs:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'module'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBTagSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'tag'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'name', 'parent_id', 'entity_id', 'entity_type']
table = 'tag'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
name = self.convertFromDB(row[1], 'str', 'varchar(255)')
vistrail = self.convertFromDB(row[2], 'long', 'int')
entity_id = self.convertFromDB(row[3], 'long', 'int')
entity_type = self.convertFromDB(row[4], 'str', 'char(16)')
tag = DBTag(name=name,
id=id)
tag.db_vistrail = vistrail
tag.db_entity_id = entity_id
tag.db_entity_type = entity_type
tag.is_dirty = False
res[('tag', id)] = tag
return res
def from_sql_fast(self, obj, all_objects):
if ('vistrail', obj.db_vistrail) in all_objects:
p = all_objects[('vistrail', obj.db_vistrail)]
p.db_add_tag(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'name', 'parent_id', 'entity_id', 'entity_type']
table = 'tag'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_vistrail') and obj.db_vistrail is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_vistrail, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'tag'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBPortSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'port'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'type', 'moduleId', 'moduleName', 'name', 'spec', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'port'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
type = self.convertFromDB(row[1], 'str', 'varchar(255)')
moduleId = self.convertFromDB(row[2], 'long', 'int')
moduleName = self.convertFromDB(row[3], 'str', 'varchar(255)')
name = self.convertFromDB(row[4], 'str', 'varchar(255)')
spec = self.convertFromDB(row[5], 'str', 'varchar(4095)')
parentType = self.convertFromDB(row[6], 'str', 'char(16)')
entity_id = self.convertFromDB(row[7], 'long', 'int')
entity_type = self.convertFromDB(row[8], 'str', 'char(16)')
parent = self.convertFromDB(row[9], 'long', 'long')
port = DBPort(type=type,
moduleId=moduleId,
moduleName=moduleName,
name=name,
spec=spec,
id=id)
port.db_parentType = parentType
port.db_entity_id = entity_id
port.db_entity_type = entity_type
port.db_parent = parent
port.is_dirty = False
res[('port', id)] = port
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'connection':
p = all_objects[('connection', obj.db_parent)]
p.db_add_port(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'type', 'moduleId', 'moduleName', 'name', 'spec', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'port'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_type') and obj.db_type is not None:
columnMap['type'] = \
self.convertToDB(obj.db_type, 'str', 'varchar(255)')
if hasattr(obj, 'db_moduleId') and obj.db_moduleId is not None:
columnMap['moduleId'] = \
self.convertToDB(obj.db_moduleId, 'long', 'int')
if hasattr(obj, 'db_moduleName') and obj.db_moduleName is not None:
columnMap['moduleName'] = \
self.convertToDB(obj.db_moduleName, 'str', 'varchar(255)')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_spec') and obj.db_spec is not None:
columnMap['spec'] = \
self.convertToDB(obj.db_spec, 'str', 'varchar(4095)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'port'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBGroupSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'group_tbl'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'cache', 'name', 'namespace', 'package', 'version', 'tag', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'group_tbl'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
cache = self.convertFromDB(row[1], 'int', 'int')
name = self.convertFromDB(row[2], 'str', 'varchar(255)')
namespace = self.convertFromDB(row[3], 'str', 'varchar(255)')
package = self.convertFromDB(row[4], 'str', 'varchar(511)')
version = self.convertFromDB(row[5], 'str', 'varchar(255)')
tag = self.convertFromDB(row[6], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[7], 'str', 'char(16)')
entity_id = self.convertFromDB(row[8], 'long', 'int')
entity_type = self.convertFromDB(row[9], 'str', 'char(16)')
parent = self.convertFromDB(row[10], 'long', 'long')
group = DBGroup(cache=cache,
name=name,
namespace=namespace,
package=package,
version=version,
tag=tag,
id=id)
group.db_parentType = parentType
group.db_entity_id = entity_id
group.db_entity_type = entity_type
group.db_parent = parent
group.is_dirty = False
res[('group', id)] = group
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_module(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'cache', 'name', 'namespace', 'package', 'version', 'tag', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'group_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_cache') and obj.db_cache is not None:
columnMap['cache'] = \
self.convertToDB(obj.db_cache, 'int', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_namespace') and obj.db_namespace is not None:
columnMap['namespace'] = \
self.convertToDB(obj.db_namespace, 'str', 'varchar(255)')
if hasattr(obj, 'db_package') and obj.db_package is not None:
columnMap['package'] = \
self.convertToDB(obj.db_package, 'str', 'varchar(511)')
if hasattr(obj, 'db_version') and obj.db_version is not None:
columnMap['version'] = \
self.convertToDB(obj.db_version, 'str', 'varchar(255)')
if hasattr(obj, 'db_tag') and obj.db_tag is not None:
columnMap['tag'] = \
self.convertToDB(obj.db_tag, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
if obj.db_workflow is not None:
child = obj.db_workflow
child.db_parent = obj.db_id
if obj.db_location is not None:
child = obj.db_location
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_functions:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'group_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBLogSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'log_tbl'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'entity_type', 'version', 'name', 'last_modified', 'vistrail_id']
table = 'log_tbl'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
global_props['entity_id'] = self.convertToDB(id, 'long', 'int')
entity_type = self.convertFromDB(row[1], 'str', 'char(16)')
global_props['entity_type'] = self.convertToDB(entity_type, 'str', 'char(16)')
version = self.convertFromDB(row[2], 'str', 'char(16)')
name = self.convertFromDB(row[3], 'str', 'varchar(255)')
last_modified = self.convertFromDB(row[4], 'datetime', 'datetime')
vistrail_id = self.convertFromDB(row[5], 'long', 'int')
log = DBLog(entity_type=entity_type,
version=version,
name=name,
last_modified=last_modified,
vistrail_id=vistrail_id,
id=id)
log.is_dirty = False
res[('log', id)] = log
return res
def from_sql_fast(self, obj, all_objects):
pass
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'entity_type', 'version', 'name', 'last_modified', 'vistrail_id']
table = 'log_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_version') and obj.db_version is not None:
columnMap['version'] = \
self.convertToDB(obj.db_version, 'str', 'char(16)')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_last_modified') and obj.db_last_modified is not None:
columnMap['last_modified'] = \
self.convertToDB(obj.db_last_modified, 'datetime', 'datetime')
if hasattr(obj, 'db_vistrail_id') and obj.db_vistrail_id is not None:
columnMap['vistrail_id'] = \
self.convertToDB(obj.db_vistrail_id, 'long', 'int')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
if obj.db_id is None:
obj.db_id = lastId
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
global_props['entity_type'] = self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_id') and obj.db_id is not None:
global_props['entity_id'] = self.convertToDB(obj.db_id, 'long', 'int')
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_workflow_execs:
child.db_log = obj.db_id
for child in obj.db_machines:
child.db_log = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'log_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBMachineSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'machine'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'name', 'os', 'architecture', 'processor', 'ram', 'vt_id', 'log_id', 'entity_id', 'entity_type']
table = 'machine'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
name = self.convertFromDB(row[1], 'str', 'varchar(255)')
os = self.convertFromDB(row[2], 'str', 'varchar(255)')
architecture = self.convertFromDB(row[3], 'str', 'varchar(255)')
processor = self.convertFromDB(row[4], 'str', 'varchar(255)')
ram = self.convertFromDB(row[5], 'int', 'int')
vistrailId = self.convertFromDB(row[6], 'long', 'int')
log = self.convertFromDB(row[7], 'long', 'int')
entity_id = self.convertFromDB(row[8], 'long', 'int')
entity_type = self.convertFromDB(row[9], 'str', 'char(16)')
machine = DBMachine(name=name,
os=os,
architecture=architecture,
processor=processor,
ram=ram,
id=id)
machine.db_vistrailId = vistrailId
machine.db_log = log
machine.db_entity_id = entity_id
machine.db_entity_type = entity_type
machine.is_dirty = False
res[('machine', id)] = machine
return res
def from_sql_fast(self, obj, all_objects):
if ('log', obj.db_log) in all_objects:
p = all_objects[('log', obj.db_log)]
p.db_add_machine(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'name', 'os', 'architecture', 'processor', 'ram', 'vt_id', 'log_id', 'entity_id', 'entity_type']
table = 'machine'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_os') and obj.db_os is not None:
columnMap['os'] = \
self.convertToDB(obj.db_os, 'str', 'varchar(255)')
if hasattr(obj, 'db_architecture') and obj.db_architecture is not None:
columnMap['architecture'] = \
self.convertToDB(obj.db_architecture, 'str', 'varchar(255)')
if hasattr(obj, 'db_processor') and obj.db_processor is not None:
columnMap['processor'] = \
self.convertToDB(obj.db_processor, 'str', 'varchar(255)')
if hasattr(obj, 'db_ram') and obj.db_ram is not None:
columnMap['ram'] = \
self.convertToDB(obj.db_ram, 'int', 'int')
if hasattr(obj, 'db_vistrailId') and obj.db_vistrailId is not None:
columnMap['vt_id'] = \
self.convertToDB(obj.db_vistrailId, 'long', 'int')
if hasattr(obj, 'db_log') and obj.db_log is not None:
columnMap['log_id'] = \
self.convertToDB(obj.db_log, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'machine'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBAddSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'add_tbl'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'what', 'object_id', 'par_obj_id', 'par_obj_type', 'action_id', 'entity_id', 'entity_type']
table = 'add_tbl'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
what = self.convertFromDB(row[1], 'str', 'varchar(255)')
objectId = self.convertFromDB(row[2], 'long', 'int')
parentObjId = self.convertFromDB(row[3], 'long', 'int')
parentObjType = self.convertFromDB(row[4], 'str', 'char(16)')
action = self.convertFromDB(row[5], 'long', 'int')
entity_id = self.convertFromDB(row[6], 'long', 'int')
entity_type = self.convertFromDB(row[7], 'str', 'char(16)')
add = DBAdd(what=what,
objectId=objectId,
parentObjId=parentObjId,
parentObjType=parentObjType,
id=id)
add.db_action = action
add.db_entity_id = entity_id
add.db_entity_type = entity_type
add.is_dirty = False
res[('add', id)] = add
return res
def from_sql_fast(self, obj, all_objects):
if ('action', obj.db_action) in all_objects:
p = all_objects[('action', obj.db_action)]
p.db_add_operation(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'what', 'object_id', 'par_obj_id', 'par_obj_type', 'action_id', 'entity_id', 'entity_type']
table = 'add_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_what') and obj.db_what is not None:
columnMap['what'] = \
self.convertToDB(obj.db_what, 'str', 'varchar(255)')
if hasattr(obj, 'db_objectId') and obj.db_objectId is not None:
columnMap['object_id'] = \
self.convertToDB(obj.db_objectId, 'long', 'int')
if hasattr(obj, 'db_parentObjId') and obj.db_parentObjId is not None:
columnMap['par_obj_id'] = \
self.convertToDB(obj.db_parentObjId, 'long', 'int')
if hasattr(obj, 'db_parentObjType') and obj.db_parentObjType is not None:
columnMap['par_obj_type'] = \
self.convertToDB(obj.db_parentObjType, 'str', 'char(16)')
if hasattr(obj, 'db_action') and obj.db_action is not None:
columnMap['action_id'] = \
self.convertToDB(obj.db_action, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
if obj.db_data is not None:
child = obj.db_data
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'add_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBOtherSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'other'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'okey', 'value', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'other'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
key = self.convertFromDB(row[1], 'str', 'varchar(255)')
value = self.convertFromDB(row[2], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[3], 'str', 'char(16)')
entity_id = self.convertFromDB(row[4], 'long', 'int')
entity_type = self.convertFromDB(row[5], 'str', 'char(16)')
parent = self.convertFromDB(row[6], 'long', 'long')
other = DBOther(key=key,
value=value,
id=id)
other.db_parentType = parentType
other.db_entity_id = entity_id
other.db_entity_type = entity_type
other.db_parent = parent
other.is_dirty = False
res[('other', id)] = other
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_other(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'okey', 'value', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'other'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_key') and obj.db_key is not None:
columnMap['okey'] = \
self.convertToDB(obj.db_key, 'str', 'varchar(255)')
if hasattr(obj, 'db_value') and obj.db_value is not None:
columnMap['value'] = \
self.convertToDB(obj.db_value, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'other'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBLocationSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'location'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'x', 'y', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'location'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
x = self.convertFromDB(row[1], 'float', 'DECIMAL(18,12)')
y = self.convertFromDB(row[2], 'float', 'DECIMAL(18,12)')
parentType = self.convertFromDB(row[3], 'str', 'char(16)')
entity_id = self.convertFromDB(row[4], 'long', 'int')
entity_type = self.convertFromDB(row[5], 'str', 'char(16)')
parent = self.convertFromDB(row[6], 'long', 'long')
location = DBLocation(x=x,
y=y,
id=id)
location.db_parentType = parentType
location.db_entity_id = entity_id
location.db_entity_type = entity_type
location.db_parent = parent
location.is_dirty = False
res[('location', id)] = location
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'module':
p = all_objects[('module', obj.db_parent)]
p.db_add_location(obj)
elif obj.db_parentType == 'abstraction':
p = all_objects[('abstraction', obj.db_parent)]
p.db_add_location(obj)
elif obj.db_parentType == 'group':
p = all_objects[('group', obj.db_parent)]
p.db_add_location(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'x', 'y', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'location'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_x') and obj.db_x is not None:
columnMap['x'] = \
self.convertToDB(obj.db_x, 'float', 'DECIMAL(18,12)')
if hasattr(obj, 'db_y') and obj.db_y is not None:
columnMap['y'] = \
self.convertToDB(obj.db_y, 'float', 'DECIMAL(18,12)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'location'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBParameterSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'parameter'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'pos', 'name', 'type', 'val', 'alias', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'parameter'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
pos = self.convertFromDB(row[1], 'long', 'int')
name = self.convertFromDB(row[2], 'str', 'varchar(255)')
type = self.convertFromDB(row[3], 'str', 'varchar(255)')
val = self.convertFromDB(row[4], 'str', 'varchar(8191)')
alias = self.convertFromDB(row[5], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[6], 'str', 'char(16)')
entity_id = self.convertFromDB(row[7], 'long', 'int')
entity_type = self.convertFromDB(row[8], 'str', 'char(16)')
parent = self.convertFromDB(row[9], 'long', 'long')
parameter = DBParameter(pos=pos,
name=name,
type=type,
val=val,
alias=alias,
id=id)
parameter.db_parentType = parentType
parameter.db_entity_id = entity_id
parameter.db_entity_type = entity_type
parameter.db_parent = parent
parameter.is_dirty = False
res[('parameter', id)] = parameter
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'function':
p = all_objects[('function', obj.db_parent)]
p.db_add_parameter(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'pos', 'name', 'type', 'val', 'alias', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'parameter'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_pos') and obj.db_pos is not None:
columnMap['pos'] = \
self.convertToDB(obj.db_pos, 'long', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_type') and obj.db_type is not None:
columnMap['type'] = \
self.convertToDB(obj.db_type, 'str', 'varchar(255)')
if hasattr(obj, 'db_val') and obj.db_val is not None:
columnMap['val'] = \
self.convertToDB(obj.db_val, 'str', 'varchar(8191)')
if hasattr(obj, 'db_alias') and obj.db_alias is not None:
columnMap['alias'] = \
self.convertToDB(obj.db_alias, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'parameter'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBPluginDataSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'plugin_data'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'data', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'plugin_data'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
data = self.convertFromDB(row[1], 'str', 'varchar(8191)')
parentType = self.convertFromDB(row[2], 'str', 'char(16)')
entity_id = self.convertFromDB(row[3], 'long', 'int')
entity_type = self.convertFromDB(row[4], 'str', 'char(16)')
parent = self.convertFromDB(row[5], 'long', 'long')
plugin_data = DBPluginData(data=data,
id=id)
plugin_data.db_parentType = parentType
plugin_data.db_entity_id = entity_id
plugin_data.db_entity_type = entity_type
plugin_data.db_parent = parent
plugin_data.is_dirty = False
res[('plugin_data', id)] = plugin_data
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_plugin_data(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'data', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'plugin_data'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_data') and obj.db_data is not None:
columnMap['data'] = \
self.convertToDB(obj.db_data, 'str', 'varchar(8191)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'plugin_data'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBFunctionSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'function'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'pos', 'name', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'function'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
pos = self.convertFromDB(row[1], 'long', 'int')
name = self.convertFromDB(row[2], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[3], 'str', 'char(16)')
entity_id = self.convertFromDB(row[4], 'long', 'int')
entity_type = self.convertFromDB(row[5], 'str', 'char(16)')
parent = self.convertFromDB(row[6], 'long', 'long')
function = DBFunction(pos=pos,
name=name,
id=id)
function.db_parentType = parentType
function.db_entity_id = entity_id
function.db_entity_type = entity_type
function.db_parent = parent
function.is_dirty = False
res[('function', id)] = function
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'module':
p = all_objects[('module', obj.db_parent)]
p.db_add_function(obj)
elif obj.db_parentType == 'abstraction':
p = all_objects[('abstraction', obj.db_parent)]
p.db_add_function(obj)
elif obj.db_parentType == 'group':
p = all_objects[('group', obj.db_parent)]
p.db_add_function(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'pos', 'name', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'function'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_pos') and obj.db_pos is not None:
columnMap['pos'] = \
self.convertToDB(obj.db_pos, 'long', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_parameters:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'function'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBAbstractionSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'abstraction'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'cache', 'name', 'namespace', 'package', 'version', 'internal_version', 'tag', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'abstraction'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
cache = self.convertFromDB(row[1], 'int', 'int')
name = self.convertFromDB(row[2], 'str', 'varchar(255)')
namespace = self.convertFromDB(row[3], 'str', 'varchar(255)')
package = self.convertFromDB(row[4], 'str', 'varchar(511)')
version = self.convertFromDB(row[5], 'str', 'varchar(255)')
internal_version = self.convertFromDB(row[6], 'str', 'varchar(255)')
tag = self.convertFromDB(row[7], 'str', 'varchar(255)')
parentType = self.convertFromDB(row[8], 'str', 'char(16)')
entity_id = self.convertFromDB(row[9], 'long', 'int')
entity_type = self.convertFromDB(row[10], 'str', 'char(16)')
parent = self.convertFromDB(row[11], 'long', 'long')
abstraction = DBAbstraction(cache=cache,
name=name,
namespace=namespace,
package=package,
version=version,
internal_version=internal_version,
tag=tag,
id=id)
abstraction.db_parentType = parentType
abstraction.db_entity_id = entity_id
abstraction.db_entity_type = entity_type
abstraction.db_parent = parent
abstraction.is_dirty = False
res[('abstraction', id)] = abstraction
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_module(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'cache', 'name', 'namespace', 'package', 'version', 'internal_version', 'tag', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'abstraction'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_cache') and obj.db_cache is not None:
columnMap['cache'] = \
self.convertToDB(obj.db_cache, 'int', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_namespace') and obj.db_namespace is not None:
columnMap['namespace'] = \
self.convertToDB(obj.db_namespace, 'str', 'varchar(255)')
if hasattr(obj, 'db_package') and obj.db_package is not None:
columnMap['package'] = \
self.convertToDB(obj.db_package, 'str', 'varchar(511)')
if hasattr(obj, 'db_version') and obj.db_version is not None:
columnMap['version'] = \
self.convertToDB(obj.db_version, 'str', 'varchar(255)')
if hasattr(obj, 'db_internal_version') and obj.db_internal_version is not None:
columnMap['internal_version'] = \
self.convertToDB(obj.db_internal_version, 'str', 'varchar(255)')
if hasattr(obj, 'db_tag') and obj.db_tag is not None:
columnMap['tag'] = \
self.convertToDB(obj.db_tag, 'str', 'varchar(255)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
if obj.db_location is not None:
child = obj.db_location
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_functions:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'abstraction'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBWorkflowSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'workflow'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'entity_id', 'entity_type', 'name', 'version', 'last_modified', 'vistrail_id', 'parent_id', 'parent_type']
table = 'workflow'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
global_props['entity_id'] = self.convertToDB(id, 'long', 'int')
entity_id = self.convertFromDB(row[1], 'long', 'int')
entity_type = self.convertFromDB(row[2], 'str', 'char(16)')
global_props['entity_type'] = self.convertToDB(entity_type, 'str', 'char(16)')
name = self.convertFromDB(row[3], 'str', 'varchar(255)')
version = self.convertFromDB(row[4], 'str', 'char(16)')
last_modified = self.convertFromDB(row[5], 'datetime', 'datetime')
vistrail_id = self.convertFromDB(row[6], 'long', 'int')
parent = self.convertFromDB(row[7], 'long', 'int')
parentType = self.convertFromDB(row[8], 'str', 'char(16)')
workflow = DBWorkflow(entity_type=entity_type,
name=name,
version=version,
last_modified=last_modified,
vistrail_id=vistrail_id,
id=id)
workflow.db_entity_id = entity_id
workflow.db_parent = parent
workflow.db_parentType = parentType
workflow.is_dirty = False
res[('workflow', id)] = workflow
return res
def from_sql_fast(self, obj, all_objects):
if ('group', obj.db_parent) in all_objects:
p = all_objects[('group', obj.db_parent)]
p.db_add_workflow(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'entity_id', 'entity_type', 'name', 'version', 'last_modified', 'vistrail_id', 'parent_id', 'parent_type']
table = 'workflow'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_version') and obj.db_version is not None:
columnMap['version'] = \
self.convertToDB(obj.db_version, 'str', 'char(16)')
if hasattr(obj, 'db_last_modified') and obj.db_last_modified is not None:
columnMap['last_modified'] = \
self.convertToDB(obj.db_last_modified, 'datetime', 'datetime')
if hasattr(obj, 'db_vistrail_id') and obj.db_vistrail_id is not None:
columnMap['vistrail_id'] = \
self.convertToDB(obj.db_vistrail_id, 'long', 'int')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'int')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
if obj.db_id is None:
obj.db_id = lastId
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
global_props['entity_type'] = self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_id') and obj.db_id is not None:
global_props['entity_id'] = self.convertToDB(obj.db_id, 'long', 'int')
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_connections:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_plugin_datas:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_others:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_modules:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'workflow'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBAnnotationSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'annotation'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'akey', 'value', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'annotation'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
key = self.convertFromDB(row[1], 'str', 'varchar(255)')
value = self.convertFromDB(row[2], 'str', 'varchar(8191)')
parentType = self.convertFromDB(row[3], 'str', 'char(16)')
entity_id = self.convertFromDB(row[4], 'long', 'int')
entity_type = self.convertFromDB(row[5], 'str', 'char(16)')
parent = self.convertFromDB(row[6], 'long', 'long')
annotation = DBAnnotation(key=key,
value=value,
id=id)
annotation.db_parentType = parentType
annotation.db_entity_id = entity_id
annotation.db_entity_type = entity_type
annotation.db_parent = parent
annotation.is_dirty = False
res[('annotation', id)] = annotation
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'vistrail':
p = all_objects[('vistrail', obj.db_parent)]
p.db_add_annotation(obj)
elif obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_annotation(obj)
elif obj.db_parentType == 'module':
p = all_objects[('module', obj.db_parent)]
p.db_add_annotation(obj)
elif obj.db_parentType == 'module_exec':
p = all_objects[('module_exec', obj.db_parent)]
p.db_add_annotation(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'action':
p = all_objects[('action', obj.db_parent)]
p.db_add_annotation(obj)
elif obj.db_parentType == 'abstraction':
p = all_objects[('abstraction', obj.db_parent)]
p.db_add_annotation(obj)
elif obj.db_parentType == 'group':
p = all_objects[('group', obj.db_parent)]
p.db_add_annotation(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'akey', 'value', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'annotation'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_key') and obj.db_key is not None:
columnMap['akey'] = \
self.convertToDB(obj.db_key, 'str', 'varchar(255)')
if hasattr(obj, 'db_value') and obj.db_value is not None:
columnMap['value'] = \
self.convertToDB(obj.db_value, 'str', 'varchar(8191)')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'annotation'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBChangeSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'change_tbl'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'what', 'old_obj_id', 'new_obj_id', 'par_obj_id', 'par_obj_type', 'action_id', 'entity_id', 'entity_type']
table = 'change_tbl'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
what = self.convertFromDB(row[1], 'str', 'varchar(255)')
oldObjId = self.convertFromDB(row[2], 'long', 'int')
newObjId = self.convertFromDB(row[3], 'long', 'int')
parentObjId = self.convertFromDB(row[4], 'long', 'int')
parentObjType = self.convertFromDB(row[5], 'str', 'char(16)')
action = self.convertFromDB(row[6], 'long', 'int')
entity_id = self.convertFromDB(row[7], 'long', 'int')
entity_type = self.convertFromDB(row[8], 'str', 'char(16)')
change = DBChange(what=what,
oldObjId=oldObjId,
newObjId=newObjId,
parentObjId=parentObjId,
parentObjType=parentObjType,
id=id)
change.db_action = action
change.db_entity_id = entity_id
change.db_entity_type = entity_type
change.is_dirty = False
res[('change', id)] = change
return res
def from_sql_fast(self, obj, all_objects):
if ('action', obj.db_action) in all_objects:
p = all_objects[('action', obj.db_action)]
p.db_add_operation(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'what', 'old_obj_id', 'new_obj_id', 'par_obj_id', 'par_obj_type', 'action_id', 'entity_id', 'entity_type']
table = 'change_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_what') and obj.db_what is not None:
columnMap['what'] = \
self.convertToDB(obj.db_what, 'str', 'varchar(255)')
if hasattr(obj, 'db_oldObjId') and obj.db_oldObjId is not None:
columnMap['old_obj_id'] = \
self.convertToDB(obj.db_oldObjId, 'long', 'int')
if hasattr(obj, 'db_newObjId') and obj.db_newObjId is not None:
columnMap['new_obj_id'] = \
self.convertToDB(obj.db_newObjId, 'long', 'int')
if hasattr(obj, 'db_parentObjId') and obj.db_parentObjId is not None:
columnMap['par_obj_id'] = \
self.convertToDB(obj.db_parentObjId, 'long', 'int')
if hasattr(obj, 'db_parentObjType') and obj.db_parentObjType is not None:
columnMap['par_obj_type'] = \
self.convertToDB(obj.db_parentObjType, 'str', 'char(16)')
if hasattr(obj, 'db_action') and obj.db_action is not None:
columnMap['action_id'] = \
self.convertToDB(obj.db_action, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
if obj.db_data is not None:
child = obj.db_data
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'change_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBWorkflowExecSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'workflow_exec'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'user', 'ip', 'session', 'vt_version', 'ts_start', 'ts_end', 'parent_id', 'parent_type', 'parent_version', 'completed', 'name', 'log_id', 'entity_id', 'entity_type']
table = 'workflow_exec'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
user = self.convertFromDB(row[1], 'str', 'varchar(255)')
ip = self.convertFromDB(row[2], 'str', 'varchar(255)')
session = self.convertFromDB(row[3], 'long', 'int')
vt_version = self.convertFromDB(row[4], 'str', 'varchar(255)')
ts_start = self.convertFromDB(row[5], 'datetime', 'datetime')
ts_end = self.convertFromDB(row[6], 'datetime', 'datetime')
parent_id = self.convertFromDB(row[7], 'long', 'int')
parent_type = self.convertFromDB(row[8], 'str', 'varchar(255)')
parent_version = self.convertFromDB(row[9], 'long', 'int')
completed = self.convertFromDB(row[10], 'int', 'int')
name = self.convertFromDB(row[11], 'str', 'varchar(255)')
log = self.convertFromDB(row[12], 'long', 'int')
entity_id = self.convertFromDB(row[13], 'long', 'int')
entity_type = self.convertFromDB(row[14], 'str', 'char(16)')
workflow_exec = DBWorkflowExec(user=user,
ip=ip,
session=session,
vt_version=vt_version,
ts_start=ts_start,
ts_end=ts_end,
parent_id=parent_id,
parent_type=parent_type,
parent_version=parent_version,
completed=completed,
name=name,
id=id)
workflow_exec.db_log = log
workflow_exec.db_entity_id = entity_id
workflow_exec.db_entity_type = entity_type
workflow_exec.is_dirty = False
res[('workflow_exec', id)] = workflow_exec
return res
def from_sql_fast(self, obj, all_objects):
if ('log', obj.db_log) in all_objects:
p = all_objects[('log', obj.db_log)]
p.db_add_workflow_exec(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'user', 'ip', 'session', 'vt_version', 'ts_start', 'ts_end', 'parent_id', 'parent_type', 'parent_version', 'completed', 'name', 'log_id', 'entity_id', 'entity_type']
table = 'workflow_exec'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_user') and obj.db_user is not None:
columnMap['user'] = \
self.convertToDB(obj.db_user, 'str', 'varchar(255)')
if hasattr(obj, 'db_ip') and obj.db_ip is not None:
columnMap['ip'] = \
self.convertToDB(obj.db_ip, 'str', 'varchar(255)')
if hasattr(obj, 'db_session') and obj.db_session is not None:
columnMap['session'] = \
self.convertToDB(obj.db_session, 'long', 'int')
if hasattr(obj, 'db_vt_version') and obj.db_vt_version is not None:
columnMap['vt_version'] = \
self.convertToDB(obj.db_vt_version, 'str', 'varchar(255)')
if hasattr(obj, 'db_ts_start') and obj.db_ts_start is not None:
columnMap['ts_start'] = \
self.convertToDB(obj.db_ts_start, 'datetime', 'datetime')
if hasattr(obj, 'db_ts_end') and obj.db_ts_end is not None:
columnMap['ts_end'] = \
self.convertToDB(obj.db_ts_end, 'datetime', 'datetime')
if hasattr(obj, 'db_parent_id') and obj.db_parent_id is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent_id, 'long', 'int')
if hasattr(obj, 'db_parent_type') and obj.db_parent_type is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parent_type, 'str', 'varchar(255)')
if hasattr(obj, 'db_parent_version') and obj.db_parent_version is not None:
columnMap['parent_version'] = \
self.convertToDB(obj.db_parent_version, 'long', 'int')
if hasattr(obj, 'db_completed') and obj.db_completed is not None:
columnMap['completed'] = \
self.convertToDB(obj.db_completed, 'int', 'int')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_log') and obj.db_log is not None:
columnMap['log_id'] = \
self.convertToDB(obj.db_log, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_module_execs:
child.db_workflow_exec = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'workflow_exec'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBConnectionSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'connection_tbl'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'connection_tbl'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
parentType = self.convertFromDB(row[1], 'str', 'char(16)')
entity_id = self.convertFromDB(row[2], 'long', 'int')
entity_type = self.convertFromDB(row[3], 'str', 'char(16)')
parent = self.convertFromDB(row[4], 'long', 'long')
connection = DBConnection(id=id)
connection.db_parentType = parentType
connection.db_entity_id = entity_id
connection.db_entity_type = entity_type
connection.db_parent = parent
connection.is_dirty = False
res[('connection', id)] = connection
return res
def from_sql_fast(self, obj, all_objects):
if obj.db_parentType == 'workflow':
p = all_objects[('workflow', obj.db_parent)]
p.db_add_connection(obj)
elif obj.db_parentType == 'add':
p = all_objects[('add', obj.db_parent)]
p.db_add_data(obj)
elif obj.db_parentType == 'change':
p = all_objects[('change', obj.db_parent)]
p.db_add_data(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'parent_type', 'entity_id', 'entity_type', 'parent_id']
table = 'connection_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_parentType') and obj.db_parentType is not None:
columnMap['parent_type'] = \
self.convertToDB(obj.db_parentType, 'str', 'char(16)')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_parent') and obj.db_parent is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_parent, 'long', 'long')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_ports:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'connection_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBActionSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'action'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'prev_id', 'date', 'session', 'user', 'prune', 'parent_id', 'entity_id', 'entity_type']
table = 'action'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
prevId = self.convertFromDB(row[1], 'long', 'int')
date = self.convertFromDB(row[2], 'datetime', 'datetime')
session = self.convertFromDB(row[3], 'long', 'int')
user = self.convertFromDB(row[4], 'str', 'varchar(255)')
prune = self.convertFromDB(row[5], 'int', 'int')
vistrail = self.convertFromDB(row[6], 'long', 'int')
entity_id = self.convertFromDB(row[7], 'long', 'int')
entity_type = self.convertFromDB(row[8], 'str', 'char(16)')
action = DBAction(prevId=prevId,
date=date,
session=session,
user=user,
prune=prune,
id=id)
action.db_vistrail = vistrail
action.db_entity_id = entity_id
action.db_entity_type = entity_type
action.is_dirty = False
res[('action', id)] = action
return res
def from_sql_fast(self, obj, all_objects):
if ('vistrail', obj.db_vistrail) in all_objects:
p = all_objects[('vistrail', obj.db_vistrail)]
p.db_add_action(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'prev_id', 'date', 'session', 'user', 'prune', 'parent_id', 'entity_id', 'entity_type']
table = 'action'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_prevId') and obj.db_prevId is not None:
columnMap['prev_id'] = \
self.convertToDB(obj.db_prevId, 'long', 'int')
if hasattr(obj, 'db_date') and obj.db_date is not None:
columnMap['date'] = \
self.convertToDB(obj.db_date, 'datetime', 'datetime')
if hasattr(obj, 'db_session') and obj.db_session is not None:
columnMap['session'] = \
self.convertToDB(obj.db_session, 'long', 'int')
if hasattr(obj, 'db_user') and obj.db_user is not None:
columnMap['user'] = \
self.convertToDB(obj.db_user, 'str', 'varchar(255)')
if hasattr(obj, 'db_prune') and obj.db_prune is not None:
columnMap['prune'] = \
self.convertToDB(obj.db_prune, 'int', 'int')
if hasattr(obj, 'db_vistrail') and obj.db_vistrail is not None:
columnMap['parent_id'] = \
self.convertToDB(obj.db_vistrail, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
for child in obj.db_operations:
child.db_action = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'action'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBDeleteSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'delete_tbl'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'what', 'object_id', 'par_obj_id', 'par_obj_type', 'action_id', 'entity_id', 'entity_type']
table = 'delete_tbl'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
what = self.convertFromDB(row[1], 'str', 'varchar(255)')
objectId = self.convertFromDB(row[2], 'long', 'int')
parentObjId = self.convertFromDB(row[3], 'long', 'int')
parentObjType = self.convertFromDB(row[4], 'str', 'char(16)')
action = self.convertFromDB(row[5], 'long', 'int')
entity_id = self.convertFromDB(row[6], 'long', 'int')
entity_type = self.convertFromDB(row[7], 'str', 'char(16)')
delete = DBDelete(what=what,
objectId=objectId,
parentObjId=parentObjId,
parentObjType=parentObjType,
id=id)
delete.db_action = action
delete.db_entity_id = entity_id
delete.db_entity_type = entity_type
delete.is_dirty = False
res[('delete', id)] = delete
return res
def from_sql_fast(self, obj, all_objects):
if ('action', obj.db_action) in all_objects:
p = all_objects[('action', obj.db_action)]
p.db_add_operation(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'what', 'object_id', 'par_obj_id', 'par_obj_type', 'action_id', 'entity_id', 'entity_type']
table = 'delete_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_what') and obj.db_what is not None:
columnMap['what'] = \
self.convertToDB(obj.db_what, 'str', 'varchar(255)')
if hasattr(obj, 'db_objectId') and obj.db_objectId is not None:
columnMap['object_id'] = \
self.convertToDB(obj.db_objectId, 'long', 'int')
if hasattr(obj, 'db_parentObjId') and obj.db_parentObjId is not None:
columnMap['par_obj_id'] = \
self.convertToDB(obj.db_parentObjId, 'long', 'int')
if hasattr(obj, 'db_parentObjType') and obj.db_parentObjType is not None:
columnMap['par_obj_type'] = \
self.convertToDB(obj.db_parentObjType, 'str', 'char(16)')
if hasattr(obj, 'db_action') and obj.db_action is not None:
columnMap['action_id'] = \
self.convertToDB(obj.db_action, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
pass
def delete_sql_column(self, db, obj, global_props):
table = 'delete_tbl'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBVistrailSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'vistrail'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'entity_type', 'version', 'name', 'last_modified']
table = 'vistrail'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
global_props['entity_id'] = self.convertToDB(id, 'long', 'int')
entity_type = self.convertFromDB(row[1], 'str', 'char(16)')
global_props['entity_type'] = self.convertToDB(entity_type, 'str', 'char(16)')
version = self.convertFromDB(row[2], 'str', 'char(16)')
name = self.convertFromDB(row[3], 'str', 'varchar(255)')
last_modified = self.convertFromDB(row[4], 'datetime', 'datetime')
vistrail = DBVistrail(entity_type=entity_type,
version=version,
name=name,
last_modified=last_modified,
id=id)
vistrail.is_dirty = False
res[('vistrail', id)] = vistrail
return res
def from_sql_fast(self, obj, all_objects):
pass
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'entity_type', 'version', 'name', 'last_modified']
table = 'vistrail'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_version') and obj.db_version is not None:
columnMap['version'] = \
self.convertToDB(obj.db_version, 'str', 'char(16)')
if hasattr(obj, 'db_name') and obj.db_name is not None:
columnMap['name'] = \
self.convertToDB(obj.db_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_last_modified') and obj.db_last_modified is not None:
columnMap['last_modified'] = \
self.convertToDB(obj.db_last_modified, 'datetime', 'datetime')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
if obj.db_id is None:
obj.db_id = lastId
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
global_props['entity_type'] = self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
if hasattr(obj, 'db_id') and obj.db_id is not None:
global_props['entity_id'] = self.convertToDB(obj.db_id, 'long', 'int')
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_actions:
child.db_vistrail = obj.db_id
for child in obj.db_tags:
child.db_vistrail = obj.db_id
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'vistrail'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
class DBModuleExecSQLDAOBase(SQLDAO):
def __init__(self, daoList):
self.daoList = daoList
self.table = 'module_exec'
def getDao(self, dao):
return self.daoList[dao]
def get_sql_columns(self, db, global_props,lock=False):
columns = ['id', 'ts_start', 'ts_end', 'cached', 'module_id', 'module_name', 'completed', 'error', 'abstraction_id', 'abstraction_version', 'machine_id', 'wf_exec_id', 'entity_id', 'entity_type']
table = 'module_exec'
whereMap = global_props
orderBy = 'id'
dbCommand = self.createSQLSelect(table, columns, whereMap, orderBy, lock)
data = self.executeSQL(db, dbCommand, True)
res = {}
for row in data:
id = self.convertFromDB(row[0], 'long', 'int')
ts_start = self.convertFromDB(row[1], 'datetime', 'datetime')
ts_end = self.convertFromDB(row[2], 'datetime', 'datetime')
cached = self.convertFromDB(row[3], 'int', 'int')
module_id = self.convertFromDB(row[4], 'long', 'int')
module_name = self.convertFromDB(row[5], 'str', 'varchar(255)')
completed = self.convertFromDB(row[6], 'int', 'int')
error = self.convertFromDB(row[7], 'str', 'varchar(1023)')
abstraction_id = self.convertFromDB(row[8], 'long', 'int')
abstraction_version = self.convertFromDB(row[9], 'long', 'int')
machine_id = self.convertFromDB(row[10], 'long', 'int')
workflow_exec = self.convertFromDB(row[11], 'long', 'int')
entity_id = self.convertFromDB(row[12], 'long', 'int')
entity_type = self.convertFromDB(row[13], 'str', 'char(16)')
module_exec = DBModuleExec(ts_start=ts_start,
ts_end=ts_end,
cached=cached,
module_id=module_id,
module_name=module_name,
completed=completed,
error=error,
abstraction_id=abstraction_id,
abstraction_version=abstraction_version,
machine_id=machine_id,
id=id)
module_exec.db_workflow_exec = workflow_exec
module_exec.db_entity_id = entity_id
module_exec.db_entity_type = entity_type
module_exec.is_dirty = False
res[('module_exec', id)] = module_exec
return res
def from_sql_fast(self, obj, all_objects):
if ('workflow_exec', obj.db_workflow_exec) in all_objects:
p = all_objects[('workflow_exec', obj.db_workflow_exec)]
p.db_add_module_exec(obj)
def set_sql_columns(self, db, obj, global_props, do_copy=True):
if not do_copy and not obj.is_dirty:
return
columns = ['id', 'ts_start', 'ts_end', 'cached', 'module_id', 'module_name', 'completed', 'error', 'abstraction_id', 'abstraction_version', 'machine_id', 'wf_exec_id', 'entity_id', 'entity_type']
table = 'module_exec'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
columnMap = {}
if hasattr(obj, 'db_id') and obj.db_id is not None:
columnMap['id'] = \
self.convertToDB(obj.db_id, 'long', 'int')
if hasattr(obj, 'db_ts_start') and obj.db_ts_start is not None:
columnMap['ts_start'] = \
self.convertToDB(obj.db_ts_start, 'datetime', 'datetime')
if hasattr(obj, 'db_ts_end') and obj.db_ts_end is not None:
columnMap['ts_end'] = \
self.convertToDB(obj.db_ts_end, 'datetime', 'datetime')
if hasattr(obj, 'db_cached') and obj.db_cached is not None:
columnMap['cached'] = \
self.convertToDB(obj.db_cached, 'int', 'int')
if hasattr(obj, 'db_module_id') and obj.db_module_id is not None:
columnMap['module_id'] = \
self.convertToDB(obj.db_module_id, 'long', 'int')
if hasattr(obj, 'db_module_name') and obj.db_module_name is not None:
columnMap['module_name'] = \
self.convertToDB(obj.db_module_name, 'str', 'varchar(255)')
if hasattr(obj, 'db_completed') and obj.db_completed is not None:
columnMap['completed'] = \
self.convertToDB(obj.db_completed, 'int', 'int')
if hasattr(obj, 'db_error') and obj.db_error is not None:
columnMap['error'] = \
self.convertToDB(obj.db_error, 'str', 'varchar(1023)')
if hasattr(obj, 'db_abstraction_id') and obj.db_abstraction_id is not None:
columnMap['abstraction_id'] = \
self.convertToDB(obj.db_abstraction_id, 'long', 'int')
if hasattr(obj, 'db_abstraction_version') and obj.db_abstraction_version is not None:
columnMap['abstraction_version'] = \
self.convertToDB(obj.db_abstraction_version, 'long', 'int')
if hasattr(obj, 'db_machine_id') and obj.db_machine_id is not None:
columnMap['machine_id'] = \
self.convertToDB(obj.db_machine_id, 'long', 'int')
if hasattr(obj, 'db_workflow_exec') and obj.db_workflow_exec is not None:
columnMap['wf_exec_id'] = \
self.convertToDB(obj.db_workflow_exec, 'long', 'int')
if hasattr(obj, 'db_entity_id') and obj.db_entity_id is not None:
columnMap['entity_id'] = \
self.convertToDB(obj.db_entity_id, 'long', 'int')
if hasattr(obj, 'db_entity_type') and obj.db_entity_type is not None:
columnMap['entity_type'] = \
self.convertToDB(obj.db_entity_type, 'str', 'char(16)')
columnMap.update(global_props)
if obj.is_new or do_copy:
dbCommand = self.createSQLInsert(table, columnMap)
else:
dbCommand = self.createSQLUpdate(table, columnMap, whereMap)
lastId = self.executeSQL(db, dbCommand, False)
def to_sql_fast(self, obj, do_copy=True):
for child in obj.db_annotations:
child.db_parentType = obj.vtType
child.db_parent = obj.db_id
def delete_sql_column(self, db, obj, global_props):
table = 'module_exec'
whereMap = {}
whereMap.update(global_props)
if obj.db_id is not None:
keyStr = self.convertToDB(obj.db_id, 'long', 'int')
whereMap['id'] = keyStr
dbCommand = self.createSQLDelete(table, whereMap)
self.executeSQL(db, dbCommand, False)
"""generated automatically by auto_dao.py"""
class SQLDAOListBase(dict):
def __init__(self, daos=None):
if daos is not None:
dict.update(self, daos)
if 'portSpec' not in self:
self['portSpec'] = DBPortSpecSQLDAOBase(self)
if 'module' not in self:
self['module'] = DBModuleSQLDAOBase(self)
if 'tag' not in self:
self['tag'] = DBTagSQLDAOBase(self)
if 'port' not in self:
self['port'] = DBPortSQLDAOBase(self)
if 'group' not in self:
self['group'] = DBGroupSQLDAOBase(self)
if 'log' not in self:
self['log'] = DBLogSQLDAOBase(self)
if 'machine' not in self:
self['machine'] = DBMachineSQLDAOBase(self)
if 'add' not in self:
self['add'] = DBAddSQLDAOBase(self)
if 'other' not in self:
self['other'] = DBOtherSQLDAOBase(self)
if 'location' not in self:
self['location'] = DBLocationSQLDAOBase(self)
if 'parameter' not in self:
self['parameter'] = DBParameterSQLDAOBase(self)
if 'plugin_data' not in self:
self['plugin_data'] = DBPluginDataSQLDAOBase(self)
if 'function' not in self:
self['function'] = DBFunctionSQLDAOBase(self)
if 'abstraction' not in self:
self['abstraction'] = DBAbstractionSQLDAOBase(self)
if 'workflow' not in self:
self['workflow'] = DBWorkflowSQLDAOBase(self)
if 'annotation' not in self:
self['annotation'] = DBAnnotationSQLDAOBase(self)
if 'change' not in self:
self['change'] = DBChangeSQLDAOBase(self)
if 'workflow_exec' not in self:
self['workflow_exec'] = DBWorkflowExecSQLDAOBase(self)
if 'connection' not in self:
self['connection'] = DBConnectionSQLDAOBase(self)
if 'action' not in self:
self['action'] = DBActionSQLDAOBase(self)
if 'delete' not in self:
self['delete'] = DBDeleteSQLDAOBase(self)
if 'vistrail' not in self:
self['vistrail'] = DBVistrailSQLDAOBase(self)
if 'module_exec' not in self:
self['module_exec'] = DBModuleExecSQLDAOBase(self)
| {
"content_hash": "b3c3d1ed664464b57d0e37dcb1340940",
"timestamp": "",
"source": "github",
"line_count": 2679,
"max_line_length": 203,
"avg_line_length": 44.63157894736842,
"alnum_prop": 0.5464338284490834,
"repo_name": "hjanime/VisTrails",
"id": "4d07c2a5dc97acd8795e089e2046ce23121ced6a",
"size": "121482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vistrails/db/versions/v0_9_4/persistence/sql/auto_gen.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1421"
},
{
"name": "Inno Setup",
"bytes": "19550"
},
{
"name": "Makefile",
"bytes": "768"
},
{
"name": "Mako",
"bytes": "66613"
},
{
"name": "PHP",
"bytes": "49302"
},
{
"name": "Python",
"bytes": "19803915"
},
{
"name": "R",
"bytes": "782836"
},
{
"name": "Ruby",
"bytes": "875"
},
{
"name": "Shell",
"bytes": "35024"
},
{
"name": "TeX",
"bytes": "145333"
},
{
"name": "XSLT",
"bytes": "1090"
}
],
"symlink_target": ""
} |
% Computes a quality value for the given inside-outside map based on size and
% compactness
%
% Copyright (C) 2013 Anestis Papazoglou
%
% You can redistribute and/or modify this software for non-commercial use
% 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/>.
%
% For commercial use, contact the author for licensing options.
%
% Contact: [email protected]
function quality = getFrameQuality( frame )
% Note: A god frame is one that has a single, high confidence blob
[ height, width ] = size( frame );
data = reshape( frame, [], 1 );
quality = sum( data );
if( quality == 0 ), return, end;
rowId = 1: height;
columnId = 1: width;
rowId = bsxfun( @times, ones( size( frame ) ), rowId' );
columnId = bsxfun( @times, ones( size( frame ) ), columnId );
x = reshape( frame .* rowId, [], 1 );
y = reshape( frame .* columnId, [], 1 );
meanx = sum( x ) / quality;
meany = sum( y ) / quality;
x = reshape( ( rowId - meanx ), [], 1 );
y = reshape( ( columnId - meany ), [], 1 );
varx = ( data .* x )' * x / quality;
vary = ( data .* y )' * y / quality;
%keyboard
variability = sqrt( varx * varx + vary * vary );
if( variability == 0 ), quality = 0; return, end
quality = quality / ( variability ^ 2 );
end
| {
"content_hash": "91d915fbb067e99eb3b12bdb48845221",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 77,
"avg_line_length": 31.816666666666666,
"alnum_prop": 0.6139339968569932,
"repo_name": "subtri/streaming_VOP_clustering",
"id": "8e14e1345f65b961cd1107fe6e2484324699afa6",
"size": "1909",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "external/FastVideoSegment/Code/Integral Intersections/getFrameQuality.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "41386"
},
{
"name": "C++",
"bytes": "2315140"
},
{
"name": "CSS",
"bytes": "1002"
},
{
"name": "HTML",
"bytes": "695036"
},
{
"name": "Matlab",
"bytes": "1174925"
},
{
"name": "Shell",
"bytes": "161"
}
],
"symlink_target": ""
} |
<?php
class Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent extends Google_Collection
{
protected $collection_key = 'suggestions';
public $description;
protected $mediaType = 'Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia';
protected $mediaDataType = '';
protected $suggestionsType = 'Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion';
protected $suggestionsDataType = 'array';
public $title;
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
/**
* @param Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia
*/
public function setMedia(Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia $media)
{
$this->media = $media;
}
/**
* @return Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmCardContentRbmMedia
*/
public function getMedia()
{
return $this->media;
}
/**
* @param Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion[]
*/
public function setSuggestions($suggestions)
{
$this->suggestions = $suggestions;
}
/**
* @return Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1IntentMessageRbmSuggestion[]
*/
public function getSuggestions()
{
return $this->suggestions;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
| {
"content_hash": "ea06f214ec2f6a09c1f3d6afa386c33f",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 124,
"avg_line_length": 28.551724137931036,
"alnum_prop": 0.7536231884057971,
"repo_name": "bshaffer/google-api-php-client-services",
"id": "4db2cb2b455e4a04bc8669dc321ea3622872760f",
"size": "2246",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Google/Service/Dialogflow/GoogleCloudDialogflowV2beta1IntentMessageRbmCardContent.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "9540154"
}
],
"symlink_target": ""
} |
/* Desc: RaySensor proximity sensor
* Author: Nate Koenig
* Date: 23 february 2004
*/
#ifndef _RAYSENSOR_HH_
#define _RAYSENSOR_HH_
#include <vector>
#include <string>
#include "math/Angle.hh"
#include "math/Pose.hh"
#include "transport/TransportTypes.hh"
#include "sensors/Sensor.hh"
namespace gazebo
{
class OgreDynamicLines;
class Collision;
class MultiRayShape;
/// \ingroup gazebo_sensors
/// \brief Sensors namespace
namespace sensors
{
/// \addtogroup gazebo_sensors
/// \{
/// \class RaySensor RaySensor.hh sensors/sensors.hh
/// \brief Sensor with one or more rays.
///
/// This sensor cast rays into the world, tests for intersections, and
/// reports the range to the nearest object. It is used by ranging
/// sensor models (e.g., sonars and scanning laser range finders).
class RaySensor: public Sensor
{
/// \brief Constructor
public: RaySensor();
/// \brief Destructor
public: virtual ~RaySensor();
// Documentation inherited
public: virtual void Load(const std::string &_worldName);
// Documentation inherited
public: virtual void Init();
// Documentation inherited
protected: virtual void UpdateImpl(bool _force);
// Documentation inherited
protected: virtual void Fini();
// Documentation inherited
public: virtual std::string GetTopic() const;
/// \brief Get the minimum angle
/// \return The minimum angle object
public: math::Angle GetAngleMin() const;
/// \brief Get the maximum angle
/// \return the maximum angle object
public: math::Angle GetAngleMax() const;
/// \brief Get the angle in radians between each range
/// \return Resolution of the angle
public: double GetAngleResolution() const;
/// \brief Get the minimum range
/// \return The minimum range
public: double GetRangeMin() const;
/// \brief Get the maximum range
/// \return The maximum range
public: double GetRangeMax() const;
/// \brief Get the range resolution
/// \return Resolution of the range
public: double GetRangeResolution() const;
/// \brief Get the ray count
/// \return The number of rays
public: int GetRayCount() const;
/// \brief Get the range count
/// \return The number of ranges
public: int GetRangeCount() const;
/// \brief Get the vertical scan line count
/// \return The number of scan lines vertically
public: int GetVerticalRayCount() const;
/// \brief Get the vertical scan line count
/// \return The number of scan lines vertically
public: int GetVerticalRangeCount() const;
/// \brief Get the vertical scan bottom angle
/// \return The minimum angle of the scan block
public: math::Angle GetVerticalAngleMin() const;
/// \brief Get the vertical scan line top angle
/// \return The Maximum angle of the scan block
public: math::Angle GetVerticalAngleMax() const;
/// \brief Get detected range for a ray.
/// Warning: If you are accessing all the ray data in a loop
/// it's possible that the Ray will update in the middle of
/// your access loop. This means some data will come from one
/// scan, and some from another scan. You can solve this
/// problem by using SetActive(false) <your accessor loop>
/// SetActive(true).
/// \param[in] _index Index of specific ray
/// \return Returns DBL_MAX for no detection.
public: double GetRange(int _index);
/// \brief Get all the ranges
/// \param _ranges A vector that will contain all the range data
public: void GetRanges(std::vector<double> &_ranges);
/// \brief Get detected retro (intensity) value for a ray.
/// Warning: If you are accessing all the ray data in a loop
/// it's possible that the Ray will update in the middle of
/// your access loop. This means some data will come from one
/// scan, and some from another scan. You can solve this
/// problem by using SetActive(false) <your accessor loop>
/// SetActive(true).
/// \param[in] _index Index of specific ray
/// \return Retro (intensity) value for ray
public: double GetRetro(int _index);
/// \brief Get detected fiducial value for a ray.
/// Warning: If you are accessing all the ray data in a loop
/// it's possible that the Ray will update in the middle of
/// your access loop. This means some data will come from one
/// scan, and some from another scan. You can solve this
/// problem by using SetActive(false) <your accessor loop>
/// SetActive(true).
/// \param[in] _index Index value of specific ray
/// \return Fiducial value
public: int GetFiducial(int _index);
/// \brief Returns a pointer to the internal physics::MultiRayShape
/// \return Pointer to ray shape
public: physics::MultiRayShapePtr GetLaserShape() const
{return this->laserShape;}
// Documentation inherited
public: virtual bool IsActive();
private: physics::CollisionPtr laserCollision;
private: physics::MultiRayShapePtr laserShape;
private: physics::EntityPtr parentEntity;
private: transport::PublisherPtr scanPub;
private: boost::mutex mutex;
private: msgs::LaserScanStamped laserMsg;
// Which noise type we support
private: enum NoiseModelType
{
NONE,
GAUSSIAN
};
// If true, apply the noise model specified by other noise parameters
private: bool noiseActive;
// Which type of noise we're applying
private: enum NoiseModelType noiseType;
// If noiseType==GAUSSIAN, noiseMean is the mean of the distibution
// from which we sample
private: double noiseMean;
// If noiseType==GAUSSIAN, noiseStdDev is the standard devation of
// the distibution from which we sample
private: double noiseStdDev;
};
/// \}
}
}
#endif
| {
"content_hash": "6a046556e79a942046ee6fe33942207a",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 75,
"avg_line_length": 34.35164835164835,
"alnum_prop": 0.6353166986564299,
"repo_name": "thomas-moulard/gazebo-deb",
"id": "437d2eb3765e20cc9a4789b4e447c054e09ccbde",
"size": "6868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gazebo/sensors/RaySensor.hh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "652008"
},
{
"name": "C++",
"bytes": "6417236"
},
{
"name": "JavaScript",
"bytes": "25255"
}
],
"symlink_target": ""
} |
'use strict';
let BaseRole = require('base-role');
class Harvester extends BaseRole {
static key() {
return 'harvester';
}
isViable() {
for (var i = 0; i < this.creep.body.length; i++) {
var part = this.creep.body[i];
if (part.hits < 1) {
return false;
}
}
return true;
}
run() {
let source = Game.getObjectById(this.memory.targetSourceId),
enemies = source.pos.findInRange(Game.HOSTILE_CREEPS, 4);
if (!this.isViable()) {
this.creep.suicide();
} else if (this.memory.fallbackLocation && enemies.length > 0) {
let l = this.memory.fallbackLocation;
this.creep.moveTo(l.x, l.y);
} else if (this.creep.energy < this.creep.energyCapacity) {
if (source && source.energy > 10) {
this.creep.moveTo(source);
this.creep.harvest(source);
} else {
console.log('Harvester source invalid!', JSON.stringify(this.memory));
}
} else {
this.creep.moveTo(this.spawn);
this.creep.transferEnergy(this.spawn);
}
}
}
module.exports = Harvester;
| {
"content_hash": "3341fc8fc456de44015a953e7c20fe9e",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 86,
"avg_line_length": 28.227272727272727,
"alnum_prop": 0.5241545893719807,
"repo_name": "boushley/screeps",
"id": "16c3ec554050176d961ef17d28e12d8190d4acd5",
"size": "1242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/harvester.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "30102"
}
],
"symlink_target": ""
} |
package com.feedsome.daq.test.service;
import org.apache.camel.EndpointInject;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import javax.validation.ConstraintViolationException;
@RunWith(SpringRunner.class)
@Import({
CamelAutoConfiguration.class,
ValidationConfiguration.class,
CamelMessageSenderTester.TestConfiguration.class
})
public class CamelMessageSenderTester {
@Configuration
static class TestConfiguration {
@Bean
public MessageSender messageSender() {
return new CamelMessageSender();
}
}
private static final String sendMessageUriMock = "mock:feed:send";
@EndpointInject(uri = sendMessageUriMock)
private MockEndpoint mockEndpoint;
@Autowired
private MessageSender messageSender;
@After
public void tearDown() throws Exception {
mockEndpoint.reset();
}
@Test(expected = ConstraintViolationException.class)
public void testSend_whenMessageIsNull_Throws_ConstraintViolationException() {
messageSender.send(null, sendMessageUriMock);
}
@Test(expected = ConstraintViolationException.class)
public void testSend_whenMessageIsEmpty_Throws_ConstraintViolationException() {
messageSender.send("", sendMessageUriMock);
}
@Test(expected = ConstraintViolationException.class)
public void testSend_whenMessageIsBlank_Throws_ConstraintViolationException() {
messageSender.send(" ", sendMessageUriMock);
}
@Test(expected = ConstraintViolationException.class)
public void testSend_whenEndpointUriIsNull_Throws_ConstraintViolationException() {
messageSender.send("plaintext message", null);
}
@Test(expected = ConstraintViolationException.class)
public void testSend_whenEndpointUriIsEmpty_Throws_ConstraintViolationException() {
messageSender.send("plaintext message", "");
}
@Test(expected = ConstraintViolationException.class)
public void testSend_whenEndpointUriIsBlank_Throws_ConstraintViolationException() {
messageSender.send("plaintext message", " ");
}
@Test
public void testSend_sendsMessageToEndpoint() throws Exception {
final String messageBody = "plaintext message";
messageSender.send(messageBody, sendMessageUriMock);
mockEndpoint.whenAnyExchangeReceived((processor) -> {
final String body = processor.getIn().getBody(String.class);
Assert.assertEquals(messageBody, body);
});
mockEndpoint.expectedMessageCount(1);
mockEndpoint.assertIsSatisfied();
}
}
| {
"content_hash": "0c9d1bb47c5a1c9707540179deca3a19",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 87,
"avg_line_length": 31.3265306122449,
"alnum_prop": 0.7420195439739413,
"repo_name": "feedsome/feedsome-daq-parent",
"id": "0219763d32d6322983529420e4e2a24a00abf0a5",
"size": "3070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "feedsome-daq-test/src/test/java/com/feedsome/daq/test/service/CamelMessageSenderTester.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "32440"
}
],
"symlink_target": ""
} |
import sys
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.version_info < (2, 5):
raise NotImplementedError("Sorry, you need at least Python 2.5 or"
" Python 3.x to use bottle.")
import rossion
setup(name="rossion",
version=rossion.__version__,
py_modules=['rossion'],
author=rossion.__author__,
author_email="[email protected]",
url="https://github.com/markgao/rossion",
license="http://www.apache.org/licenses/LICENSE-2.0",
description="Fast and simple session module for tornado app",
long_description=rossion.__doc__,
platforms="any",
install_requires=[
"pylibmc>=1.5.0",
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
) | {
"content_hash": "0d83d87572273c8daefb64257de69624",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 72,
"avg_line_length": 33,
"alnum_prop": 0.5978705978705978,
"repo_name": "markgao/rossion",
"id": "5e4e6c921465143c1c57919923e35b9bab518f49",
"size": "1818",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "8653"
}
],
"symlink_target": ""
} |
'use strict';
var FontInspector = function FontInspectorClosure() {
var fonts;
var active = false;
var fontAttribute = 'data-font-name';
function removeSelection() {
var divs = document.querySelectorAll('div[' + fontAttribute + ']');
for (var i = 0, ii = divs.length; i < ii; ++i) {
var div = divs[i];
div.className = '';
}
}
function resetSelection() {
var divs = document.querySelectorAll('div[' + fontAttribute + ']');
for (var i = 0, ii = divs.length; i < ii; ++i) {
var div = divs[i];
div.className = 'debuggerHideText';
}
}
function selectFont(fontName, show) {
var divs = document.querySelectorAll('div[' + fontAttribute + '=' + fontName + ']');
for (var i = 0, ii = divs.length; i < ii; ++i) {
var div = divs[i];
div.className = show ? 'debuggerShowText' : 'debuggerHideText';
}
}
function textLayerClick(e) {
if (!e.target.dataset.fontName || e.target.tagName.toUpperCase() !== 'DIV') {
return;
}
var fontName = e.target.dataset.fontName;
var selects = document.getElementsByTagName('input');
for (var i = 0; i < selects.length; ++i) {
var select = selects[i];
if (select.dataset.fontName !== fontName) {
continue;
}
select.checked = !select.checked;
selectFont(fontName, select.checked);
select.scrollIntoView();
}
}
return {
id: 'FontInspector',
name: 'Font Inspector',
panel: null,
manager: null,
init: function init(pdfjsLib) {
var panel = this.panel;
panel.setAttribute('style', 'padding: 5px;');
var tmp = document.createElement('button');
tmp.addEventListener('click', resetSelection);
tmp.textContent = 'Refresh';
panel.appendChild(tmp);
fonts = document.createElement('div');
panel.appendChild(fonts);
},
cleanup: function cleanup() {
fonts.textContent = '';
},
enabled: false,
get active() {
return active;
},
set active(value) {
active = value;
if (active) {
document.body.addEventListener('click', textLayerClick, true);
resetSelection();
} else {
document.body.removeEventListener('click', textLayerClick, true);
removeSelection();
}
},
fontAdded: function fontAdded(fontObj, url) {
function properties(obj, list) {
var moreInfo = document.createElement('table');
for (var i = 0; i < list.length; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
td1.textContent = list[i];
tr.appendChild(td1);
var td2 = document.createElement('td');
td2.textContent = obj[list[i]].toString();
tr.appendChild(td2);
moreInfo.appendChild(tr);
}
return moreInfo;
}
var moreInfo = properties(fontObj, ['name', 'type']);
var fontName = fontObj.loadedName;
var font = document.createElement('div');
var name = document.createElement('span');
name.textContent = fontName;
var download = document.createElement('a');
if (url) {
url = /url\(['"]?([^\)"']+)/.exec(url);
download.href = url[1];
} else if (fontObj.data) {
url = URL.createObjectURL(new Blob([fontObj.data], { type: fontObj.mimeType }));
download.href = url;
}
download.textContent = 'Download';
var logIt = document.createElement('a');
logIt.href = '';
logIt.textContent = 'Log';
logIt.addEventListener('click', function (event) {
event.preventDefault();
console.log(fontObj);
});
var select = document.createElement('input');
select.setAttribute('type', 'checkbox');
select.dataset.fontName = fontName;
select.addEventListener('click', function (select, fontName) {
return function () {
selectFont(fontName, select.checked);
};
}(select, fontName));
font.appendChild(select);
font.appendChild(name);
font.appendChild(document.createTextNode(' '));
font.appendChild(download);
font.appendChild(document.createTextNode(' '));
font.appendChild(logIt);
font.appendChild(moreInfo);
fonts.appendChild(font);
setTimeout(function () {
if (this.active) {
resetSelection();
}
}.bind(this), 2000);
}
};
}();
var opMap;
var StepperManager = function StepperManagerClosure() {
var steppers = [];
var stepperDiv = null;
var stepperControls = null;
var stepperChooser = null;
var breakPoints = Object.create(null);
return {
id: 'Stepper',
name: 'Stepper',
panel: null,
manager: null,
init: function init(pdfjsLib) {
var self = this;
this.panel.setAttribute('style', 'padding: 5px;');
stepperControls = document.createElement('div');
stepperChooser = document.createElement('select');
stepperChooser.addEventListener('change', function (event) {
self.selectStepper(this.value);
});
stepperControls.appendChild(stepperChooser);
stepperDiv = document.createElement('div');
this.panel.appendChild(stepperControls);
this.panel.appendChild(stepperDiv);
if (sessionStorage.getItem('pdfjsBreakPoints')) {
breakPoints = JSON.parse(sessionStorage.getItem('pdfjsBreakPoints'));
}
opMap = Object.create(null);
for (var key in pdfjsLib.OPS) {
opMap[pdfjsLib.OPS[key]] = key;
}
},
cleanup: function cleanup() {
stepperChooser.textContent = '';
stepperDiv.textContent = '';
steppers = [];
},
enabled: false,
active: false,
create: function create(pageIndex) {
var debug = document.createElement('div');
debug.id = 'stepper' + pageIndex;
debug.setAttribute('hidden', true);
debug.className = 'stepper';
stepperDiv.appendChild(debug);
var b = document.createElement('option');
b.textContent = 'Page ' + (pageIndex + 1);
b.value = pageIndex;
stepperChooser.appendChild(b);
var initBreakPoints = breakPoints[pageIndex] || [];
var stepper = new Stepper(debug, pageIndex, initBreakPoints);
steppers.push(stepper);
if (steppers.length === 1) {
this.selectStepper(pageIndex, false);
}
return stepper;
},
selectStepper: function selectStepper(pageIndex, selectPanel) {
var i;
pageIndex = pageIndex | 0;
if (selectPanel) {
this.manager.selectPanel(this);
}
for (i = 0; i < steppers.length; ++i) {
var stepper = steppers[i];
if (stepper.pageIndex === pageIndex) {
stepper.panel.removeAttribute('hidden');
} else {
stepper.panel.setAttribute('hidden', true);
}
}
var options = stepperChooser.options;
for (i = 0; i < options.length; ++i) {
var option = options[i];
option.selected = (option.value | 0) === pageIndex;
}
},
saveBreakPoints: function saveBreakPoints(pageIndex, bps) {
breakPoints[pageIndex] = bps;
sessionStorage.setItem('pdfjsBreakPoints', JSON.stringify(breakPoints));
}
};
}();
var Stepper = function StepperClosure() {
function c(tag, textContent) {
var d = document.createElement(tag);
if (textContent) {
d.textContent = textContent;
}
return d;
}
function simplifyArgs(args) {
if (typeof args === 'string') {
var MAX_STRING_LENGTH = 75;
return args.length <= MAX_STRING_LENGTH ? args : args.substr(0, MAX_STRING_LENGTH) + '...';
}
if (typeof args !== 'object' || args === null) {
return args;
}
if ('length' in args) {
var simpleArgs = [],
i,
ii;
var MAX_ITEMS = 10;
for (i = 0, ii = Math.min(MAX_ITEMS, args.length); i < ii; i++) {
simpleArgs.push(simplifyArgs(args[i]));
}
if (i < args.length) {
simpleArgs.push('...');
}
return simpleArgs;
}
var simpleObj = {};
for (var key in args) {
simpleObj[key] = simplifyArgs(args[key]);
}
return simpleObj;
}
function Stepper(panel, pageIndex, initialBreakPoints) {
this.panel = panel;
this.breakPoint = 0;
this.nextBreakPoint = null;
this.pageIndex = pageIndex;
this.breakPoints = initialBreakPoints;
this.currentIdx = -1;
this.operatorListIdx = 0;
}
Stepper.prototype = {
init: function init(operatorList) {
var panel = this.panel;
var content = c('div', 'c=continue, s=step');
var table = c('table');
content.appendChild(table);
table.cellSpacing = 0;
var headerRow = c('tr');
table.appendChild(headerRow);
headerRow.appendChild(c('th', 'Break'));
headerRow.appendChild(c('th', 'Idx'));
headerRow.appendChild(c('th', 'fn'));
headerRow.appendChild(c('th', 'args'));
panel.appendChild(content);
this.table = table;
this.updateOperatorList(operatorList);
},
updateOperatorList: function updateOperatorList(operatorList) {
var self = this;
function cboxOnClick() {
var x = +this.dataset.idx;
if (this.checked) {
self.breakPoints.push(x);
} else {
self.breakPoints.splice(self.breakPoints.indexOf(x), 1);
}
StepperManager.saveBreakPoints(self.pageIndex, self.breakPoints);
}
var MAX_OPERATORS_COUNT = 15000;
if (this.operatorListIdx > MAX_OPERATORS_COUNT) {
return;
}
var chunk = document.createDocumentFragment();
var operatorsToDisplay = Math.min(MAX_OPERATORS_COUNT, operatorList.fnArray.length);
for (var i = this.operatorListIdx; i < operatorsToDisplay; i++) {
var line = c('tr');
line.className = 'line';
line.dataset.idx = i;
chunk.appendChild(line);
var checked = this.breakPoints.indexOf(i) !== -1;
var args = operatorList.argsArray[i] || [];
var breakCell = c('td');
var cbox = c('input');
cbox.type = 'checkbox';
cbox.className = 'points';
cbox.checked = checked;
cbox.dataset.idx = i;
cbox.onclick = cboxOnClick;
breakCell.appendChild(cbox);
line.appendChild(breakCell);
line.appendChild(c('td', i.toString()));
var fn = opMap[operatorList.fnArray[i]];
var decArgs = args;
if (fn === 'showText') {
var glyphs = args[0];
var newArgs = [];
var str = [];
for (var j = 0; j < glyphs.length; j++) {
var glyph = glyphs[j];
if (typeof glyph === 'object' && glyph !== null) {
str.push(glyph.fontChar);
} else {
if (str.length > 0) {
newArgs.push(str.join(''));
str = [];
}
newArgs.push(glyph);
}
}
if (str.length > 0) {
newArgs.push(str.join(''));
}
decArgs = [newArgs];
}
line.appendChild(c('td', fn));
line.appendChild(c('td', JSON.stringify(simplifyArgs(decArgs))));
}
if (operatorsToDisplay < operatorList.fnArray.length) {
line = c('tr');
var lastCell = c('td', '...');
lastCell.colspan = 4;
chunk.appendChild(lastCell);
}
this.operatorListIdx = operatorList.fnArray.length;
this.table.appendChild(chunk);
},
getNextBreakPoint: function getNextBreakPoint() {
this.breakPoints.sort(function (a, b) {
return a - b;
});
for (var i = 0; i < this.breakPoints.length; i++) {
if (this.breakPoints[i] > this.currentIdx) {
return this.breakPoints[i];
}
}
return null;
},
breakIt: function breakIt(idx, callback) {
StepperManager.selectStepper(this.pageIndex, true);
var self = this;
var dom = document;
self.currentIdx = idx;
var listener = function (e) {
switch (e.keyCode) {
case 83:
dom.removeEventListener('keydown', listener);
self.nextBreakPoint = self.currentIdx + 1;
self.goTo(-1);
callback();
break;
case 67:
dom.removeEventListener('keydown', listener);
var breakPoint = self.getNextBreakPoint();
self.nextBreakPoint = breakPoint;
self.goTo(-1);
callback();
break;
}
};
dom.addEventListener('keydown', listener);
self.goTo(idx);
},
goTo: function goTo(idx) {
var allRows = this.panel.getElementsByClassName('line');
for (var x = 0, xx = allRows.length; x < xx; ++x) {
var row = allRows[x];
if ((row.dataset.idx | 0) === idx) {
row.style.backgroundColor = 'rgb(251,250,207)';
row.scrollIntoView();
} else {
row.style.backgroundColor = null;
}
}
}
};
return Stepper;
}();
var Stats = function Stats() {
var stats = [];
function clear(node) {
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}
function getStatIndex(pageNumber) {
for (var i = 0, ii = stats.length; i < ii; ++i) {
if (stats[i].pageNumber === pageNumber) {
return i;
}
}
return false;
}
return {
id: 'Stats',
name: 'Stats',
panel: null,
manager: null,
init: function init(pdfjsLib) {
this.panel.setAttribute('style', 'padding: 5px;');
pdfjsLib.PDFJS.enableStats = true;
},
enabled: false,
active: false,
add: function (pageNumber, stat) {
if (!stat) {
return;
}
var statsIndex = getStatIndex(pageNumber);
if (statsIndex !== false) {
var b = stats[statsIndex];
this.panel.removeChild(b.div);
stats.splice(statsIndex, 1);
}
var wrapper = document.createElement('div');
wrapper.className = 'stats';
var title = document.createElement('div');
title.className = 'title';
title.textContent = 'Page: ' + pageNumber;
var statsDiv = document.createElement('div');
statsDiv.textContent = stat.toString();
wrapper.appendChild(title);
wrapper.appendChild(statsDiv);
stats.push({
pageNumber: pageNumber,
div: wrapper
});
stats.sort(function (a, b) {
return a.pageNumber - b.pageNumber;
});
clear(this.panel);
for (var i = 0, ii = stats.length; i < ii; ++i) {
this.panel.appendChild(stats[i].div);
}
},
cleanup: function () {
stats = [];
clear(this.panel);
}
};
}();
window.PDFBug = function PDFBugClosure() {
var panelWidth = 300;
var buttons = [];
var activePanel = null;
return {
tools: [FontInspector, StepperManager, Stats],
enable: function (ids) {
var all = false,
tools = this.tools;
if (ids.length === 1 && ids[0] === 'all') {
all = true;
}
for (var i = 0; i < tools.length; ++i) {
var tool = tools[i];
if (all || ids.indexOf(tool.id) !== -1) {
tool.enabled = true;
}
}
if (!all) {
tools.sort(function (a, b) {
var indexA = ids.indexOf(a.id);
indexA = indexA < 0 ? tools.length : indexA;
var indexB = ids.indexOf(b.id);
indexB = indexB < 0 ? tools.length : indexB;
return indexA - indexB;
});
}
},
init: function init(pdfjsLib, container) {
var ui = document.createElement('div');
ui.id = 'PDFBug';
var controls = document.createElement('div');
controls.setAttribute('class', 'controls');
ui.appendChild(controls);
var panels = document.createElement('div');
panels.setAttribute('class', 'panels');
ui.appendChild(panels);
container.appendChild(ui);
container.style.right = panelWidth + 'px';
var tools = this.tools;
var self = this;
for (var i = 0; i < tools.length; ++i) {
var tool = tools[i];
var panel = document.createElement('div');
var panelButton = document.createElement('button');
panelButton.textContent = tool.name;
panelButton.addEventListener('click', function (selected) {
return function (event) {
event.preventDefault();
self.selectPanel(selected);
};
}(i));
controls.appendChild(panelButton);
panels.appendChild(panel);
tool.panel = panel;
tool.manager = this;
if (tool.enabled) {
tool.init(pdfjsLib);
} else {
panel.textContent = tool.name + ' is disabled. To enable add ' + ' "' + tool.id + '" to the pdfBug parameter ' + 'and refresh (separate multiple by commas).';
}
buttons.push(panelButton);
}
this.selectPanel(0);
},
cleanup: function cleanup() {
for (var i = 0, ii = this.tools.length; i < ii; i++) {
if (this.tools[i].enabled) {
this.tools[i].cleanup();
}
}
},
selectPanel: function selectPanel(index) {
if (typeof index !== 'number') {
index = this.tools.indexOf(index);
}
if (index === activePanel) {
return;
}
activePanel = index;
var tools = this.tools;
for (var j = 0; j < tools.length; ++j) {
if (j === index) {
buttons[j].setAttribute('class', 'active');
tools[j].active = true;
tools[j].panel.removeAttribute('hidden');
} else {
buttons[j].setAttribute('class', '');
tools[j].active = false;
tools[j].panel.setAttribute('hidden', 'true');
}
}
}
};
}(); | {
"content_hash": "841537ecdabaf09c5cf40dbd2ffef47d",
"timestamp": "",
"source": "github",
"line_count": 558,
"max_line_length": 168,
"avg_line_length": 32.00179211469534,
"alnum_prop": 0.5662205297642381,
"repo_name": "VanHackathon2017HueBR/presentation-builder",
"id": "01bb1c9a0f875dfd3a1632657614d378619734f0",
"size": "18455",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/components/pdfjs-dist/lib/web/debugger.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10666"
},
{
"name": "HTML",
"bytes": "34809"
},
{
"name": "JavaScript",
"bytes": "27773"
}
],
"symlink_target": ""
} |
<?php
namespace Casino\BlackjackBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CasinoBlackjackBundle extends Bundle
{
}
| {
"content_hash": "8cc00ace93891199bcdd868d3b5295c2",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 15.333333333333334,
"alnum_prop": 0.8188405797101449,
"repo_name": "ManuLEM/BlackJack",
"id": "6b1f981b326d0358ba36aba85270a6e9341f0d6a",
"size": "138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Casino/BlackjackBundle/CasinoBlackjackBundle.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "5445"
},
{
"name": "HTML",
"bytes": "8035"
},
{
"name": "PHP",
"bytes": "79039"
}
],
"symlink_target": ""
} |
namespace REngine {
class Component;
// Entity
// Represents an entity in the game world,
// contains a list of components that systems
// will use to control its interactions with
// the world.
class Entity {
public:
Entity();
~Entity();
void removeComponent(Component* c);
void addComponent(Component* c);
template<class T> T* getComponent() {
T* temp = nullptr;
for(Component* c : components) {
temp = dynamic_cast<T*>(c);
if(temp != nullptr) {
return temp;
}
}
return temp;
}
private:
std::vector<Component*> components;
};
}
#endif | {
"content_hash": "a29c4a3834273be6678aa9e5bb1a31cb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 45,
"avg_line_length": 17.705882352941178,
"alnum_prop": 0.6362126245847176,
"repo_name": "NathanRLJones/Rogue",
"id": "054630e99bbe99f2cca63db1fa2f7967a4afb87b",
"size": "662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core/entity.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "66562"
},
{
"name": "Makefile",
"bytes": "1633"
},
{
"name": "Perl",
"bytes": "1747"
}
],
"symlink_target": ""
} |
'use strict';
//define variables
var Promise = require('bluebird');
var errorUtils = require('../utils/errorUtils');
var debug = require('debug') ('content');
var errorCodes = require('../utils/errorCodes');
module.exports = function(Content) {
Content.disableRemoteMethod('find', true);
Content.disableRemoteMethod('exists', true);
Content.disableRemoteMethod('findOne', true);
Content.disableRemoteMethod('count', true);
Content.disableRemoteMethod('invoke', true);
Content.disableRemoteMethod('update', true);
Content.disableRemoteMethod('upsert', true);
Content.disableRemoteMethod('create', true);
Content.disableRemoteMethod('findById', true);
Content.disableRemoteMethod('prototype.updateAttributes', true);
Content.disableRemoteMethod('deleteById', true);
Content.disableRemoteMethod('updateAll', true);
Content.disableRemoteMethod('createChangeStream', true);
Content.disableRemoteMethod('replaceOrCreate', true);
Content.disableRemoteMethod('upsertWithWhere', true);
Content.disableRemoteMethod('replaceById', true);
/**
* Fetch all the Content. Filter would be used to filter out the results and to fetch limited data set.
* @param {string} filter filter expression provided by calling application
* @callback {Function} callback Callback function
* @param {Error|string} err Error object
* @param {Content} result Result object
*/
Content.findAllContent = function(filter, access_token, callback) {
Content.app.models.Content.find({where:filter},function(err,data){
if(err){
debug('Error occured while fetching contents');
callback(err);
}else {
callback(null,data);
}
});
}
//REMOTE METHOD DEFINITION
Content.remoteMethod('findAllContent',
{
isStatic: true,
accepts:
[ { arg: 'filter',
type: 'string',
description: 'filter expression provided by calling application',
required: false,
http: { source: 'query' }
},
{
arg: 'access_token',
type: 'string',
description: 'token to be passed as a header',
required: false,
http: {source: 'header'}
}],
returns:
[ { description: 'Successful Response',
type: 'Content',
arg: 'data',
root: true } ],
http: { verb: 'get', path: '/' },
description: 'Fetch all the Content\n'
});
/*
Private Function for updating document version
*/
exports.updateDocVersion = function (existingContent, content, callback) {
if (existingContent === undefined || existingContent.length === 0) {
content.version = '1.00';
callback(null, content);
}
else {
if ((existingContent.length > 0) && (content.version === undefined || content.version === null || content.version === '')) {
callback(errorUtils.populateError(new Error(), errorCodes.createContent.CNT100));
}
else {
var docVersion = existingContent[0].version;
if (docVersion.split('.')[1] !== 99 && content.majorVersionFlag === false) {
content.version = (docVersion.split('.')[0]) + '.' + ((parseFloat(docVersion.split('.')[1], 10) + 101).toString().substr(1));
callback(null, content);
}
else {
content.version = (parseFloat(docVersion.split('.')[0]) + 1) + '.00';
callback(null, content);
}
}
}
};
/**
* Update the Content.
* @param {Content} content
* @callback {Function} callback Callback function
* @param {Error|string} err Error object
* @param {Content} result Result object
*/
Content.updateContent = function(content, callback) {
var query = {'where': {'title': content.title}, order: 'version DESC', limit: 1};
try{
var findExistingContentP = Promise.promisify(Content.app.models.Content.find,{context: Content.app.models.Content});
var updateContentVersionP = Promise.promisify(exports.updateDocVersion);
var updateContentP = Promise.promisify(Content.app.models.Content.replaceOrCreate, {context: Content.app.models.Content});
//Promisified method call
findExistingContentP(query)
.then(function(existingContent){
return new Promise(function(resolve, reject){
updateContentVersionP(existingContent, content, function(err, data){
if(err){
reject(err);
}else {
resolve(data);
}
});
})
})
.then(updateContentP)
.then(function(result){
debug('Successfully updated content');
callback(null,result);
})
.catch(function(err){
callback(err);
})
}catch(error){
debug('Error occured while updating contents', error);
callback(error);
}
}
//REMOTE METHOD DEFINITION
Content.remoteMethod('updateContent',
{
isStatic: true,
produces: [ 'application/json' ],
accepts:
[ { arg: 'content',
type: 'Content',
description: '',
required: true,
http: { source: 'body' } } ],
returns:
[ { description: 'Successful Response',
type: 'Content',
arg: 'data',
root: true } ],
http: { verb: 'put', path: '/' },
description: 'Update the Content.\n'
}
);
/**
* Updates WorkFlow of the content.
* @param {Content} content
* @callback {Function} callback Callback function
* @param {Error|string} err Error object
* @param {Content} result Result object
*/
Content.updateWorkflow = function(content, callback) {
debug('Inside updateWorkflow method');
try{
var data = {};
data.workflowList = content.workflowList;
Content.app.models.Content.upsertWithWhere({'id': content.id}, data, function(err,result){
if(result){
debug('Successfully updated WorkFlow');
return callback(null, result);
}else{
debug('Error occured while updating WorkFlow', err);
callback(err);
}
});
}catch(error){
debug('Error occured while updating WorkFlow', error);
callback(error);
}
}
//REMOTE METHOD DEFINITION
Content.remoteMethod('updateWorkflow',
{
isStatic: true,
produces: [ 'application/json' ],
accepts:
[ { arg: 'content',
type: 'Content',
description: '',
required: true,
http: { source: 'body' } } ],
returns:
[ { description: 'Successful Response',
type: 'Content',
arg: 'data',
root: true } ],
http: { verb: 'patch', path: '/' },
description: 'Updates WorkFlow of the content.\n'
}
);
/**
* Creates the Content.
* @param {Content} content the Content to be created.
* @callback {Function} callback Callback function
* @param {Error|string} err Error object
* @param {any} result Result object
*/
Content.createContent = function(content, callback) {
debug('inside createContent method');
var query = {'where': {'title': content.title}, order: 'version DESC', limit: 1};
try{
var findExistingContentP = Promise.promisify(Content.app.models.Content.find,{context: Content.app.models.Content});
var updateContentVersionP = Promise.promisify(exports.updateDocVersion);
var createContentP = Promise.promisify(Content.app.models.Content.create, {context: Content.app.models.Content});
//Promisified method call
findExistingContentP(query)
.then(function(existingContent){
return new Promise(function(resolve, reject){
updateContentVersionP(existingContent, content, function(err, data){
if(err){
reject(err);
}else {
resolve(data);
}
});
})
})
.then(createContentP)
.then(function(result){
debug('Successfully updated content');
callback(null,result);
})
.catch(function(err){
callback(err);
})
}catch(error){
debug('Error occurred while creating content', error);
callback(error);
}
}
//REMOTE METHOD DEFINITION
Content.remoteMethod('createContent',
{ isStatic: true,
consumes: [ 'application/json' ],
accepts:
[ { arg: 'content',
type: 'Content',
description: 'the Content to be created.',
required: true,
http: { source: 'body' } } ],
returns:
[ { description: 'Successful Response',
type: 'Content',
arg: 'data',
root: true } ],
http: { verb: 'post', path: '/' },
description: 'Creates the Content.\n' }
);
};
| {
"content_hash": "e1455d6fbbe26fcefc3e58646b6c7358",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 134,
"avg_line_length": 36.28679245283019,
"alnum_prop": 0.5512687188019967,
"repo_name": "abhiyaantrikee/content-service",
"id": "039be7b55c40576f343d17de388161a6ed9d8801",
"size": "9616",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "user/common/models/content.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "58952"
}
],
"symlink_target": ""
} |
import { PeakSpectrumData, PeakSpectrumDataResults } from "./PeakSpectrumData";
import { SpectrumData } from "./SpectrumData";
declare interface HarmonicSpectrumDataResults extends PeakSpectrumDataResults {
odd_even_ratio: number
noisiness: number
}
declare class HarmonicSpectrumData extends SpectrumData {
public results: HarmonicSpectrumDataResults
constructor(N: number, sampleRate: number, parent?: PeakSpectrumData)
odd_even_ratio(): number
noisiness(): number
} | {
"content_hash": "7a2f9b5cab44c54368e27d7fe00bd993",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 79,
"avg_line_length": 33,
"alnum_prop": 0.7777777777777778,
"repo_name": "nickjillings/js-xtract",
"id": "d413d7709ff142767d0090e9b4b9953cae7f97ac",
"size": "495",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "typings/objects/HarmonicSpectrumData.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7505"
},
{
"name": "HTML",
"bytes": "7018"
},
{
"name": "JavaScript",
"bytes": "251357"
}
],
"symlink_target": ""
} |
namespace Microsoft.Graph
{
/// <summary>
/// The type DriveRecentCollectionPage.
/// </summary>
public partial class DriveRecentCollectionPage : CollectionPage<DriveItem>, IDriveRecentCollectionPage
{
/// <summary>
/// Gets the next page <see cref="IDriveRecentRequest"/> instance.
/// </summary>
public IDriveRecentRequest NextPageRequest { get; private set; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
{
if (!string.IsNullOrEmpty(nextPageLinkString))
{
this.NextPageRequest = new DriveRecentRequest(
nextPageLinkString,
client,
null);
}
}
}
}
| {
"content_hash": "f533c7b9353a27c1e5d08582a33e2961",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 106,
"avg_line_length": 32.629629629629626,
"alnum_prop": 0.5800227014755959,
"repo_name": "garethj-msft/msgraph-sdk-dotnet",
"id": "debff26c3714cb3efbcea757a28c439a5e9d563c",
"size": "1285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Microsoft.Graph/Requests/Generated/DriveRecentCollectionPage.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "9032877"
},
{
"name": "Smalltalk",
"bytes": "12638"
}
],
"symlink_target": ""
} |
<?php
if (!is_file(dirname(__DIR__).'/vendor/autoload.php')) {
throw new RuntimeException('Install dependencies to run test suite.');
}
$loader = require dirname(__DIR__).'/vendor/autoload.php';
| {
"content_hash": "f216a8957804bb6717bed51bba7c0442",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 74,
"avg_line_length": 25.25,
"alnum_prop": 0.6683168316831684,
"repo_name": "sukobuto/ginq",
"id": "0786f853de088f23f52e7333deeeefd0750803d8",
"size": "677",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/bootstrap.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "248945"
}
],
"symlink_target": ""
} |
package org.arakhne.afc.math.geometry.d3.i;
import org.junit.Ignore;
import org.arakhne.afc.math.geometry.d3.AbstractTuple3DTest;
@SuppressWarnings("all")
@Ignore("temporary")
public class Tuple3iTest extends AbstractTuple3DTest<Tuple3i> {
@Override
public boolean isIntCoordinates() {
return true;
}
@Override
public Tuple3i createTuple(double x, double y, double z) {
return new Tuple3i(x, y, z);
}
}
| {
"content_hash": "fd5bd995905588130382afa40c6a0ca7",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 63,
"avg_line_length": 18.347826086956523,
"alnum_prop": 0.7464454976303317,
"repo_name": "DevFactory/afc",
"id": "1d2c72c3628404e1c7c0aecd61fc9cb747b3d885",
"size": "1340",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/math/src/test/java/org/arakhne/afc/math/geometry/d3/i/Tuple3iTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "35"
},
{
"name": "Java",
"bytes": "13197082"
},
{
"name": "Limbo",
"bytes": "1197"
},
{
"name": "Matlab",
"bytes": "1805"
},
{
"name": "Shell",
"bytes": "3726"
}
],
"symlink_target": ""
} |
/**
* Keyboard class handles the keyboard state for the InputHandler
*/
class Keyboard {
/**
* Constructor for the Keyboard class
*/
constructor() {
// Store state
this.keys = {};
// Setup listeners for key events
document.addEventListener('keydown', (e) => this._onKeyDown(e), false);
document.addEventListener('keyup', (e) => this._onKeyUp(e), false);
}
/**
* Callback listener for keydown event
*/
_onKeyDown(e) {
this.keys[e.key.toLowerCase()] = true;
e.preventDefault();
e.stopPropagation();
}
/**
* Callback listener for keyup event
*/
_onKeyUp(e) {
this.keys[e.key.toLowerCase()] = false;
}
/**
* Check if a key is down,
* @param {string} key The key to check
*/
keyIsPressed(key) {
if (this.keys[key.toLowerCase()]) {
return true;
} else {
return false;
}
}
}
export { Keyboard as default };
| {
"content_hash": "63ea91615a683d532076681bf5b12a47",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 75,
"avg_line_length": 19.166666666666668,
"alnum_prop": 0.592391304347826,
"repo_name": "nicholasnelson/uncondemned",
"id": "858d33ae2fcb2ec0f40ac4f109b9b20cff96f1e7",
"size": "2052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/scripts/GameObjects/Player/InputHandler/Keyboard.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2095"
},
{
"name": "JavaScript",
"bytes": "1503530"
}
],
"symlink_target": ""
} |
var Bin = require('./bin');
var AxisWrapper = require('./axis-wrapper');
var Canvas = require('./canvas');
var _ = require('lodash');
var React = require('react');
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
var utils = require('lightning-client-utils');
var d3 = require('d3');
var Histogram = React.createClass({displayName: "Histogram",
mixins: [PureRenderMixin],
getDefaultProps: function() {
return {
values: [],
zoom: true
};
},
getInitialState: function() {
var bins = this.props.bins || Math.round(Math.sqrt(this.props.values.length));
var histData = d3.layout.histogram().bins(bins)(this.props.values);
return {
bins: bins,
initialBins: bins,
histData: histData
};
},
scaleX: function() {
var domain = d3.extent(this.props.values);
return d3.scale.linear().domain(domain).range([0, this.props.width]);
},
scaleY: function() {
var domain = d3.extent(this.state.histData, function(d) {
return d.y;
});
return d3.scale.linear().domain([0, domain[1]]).range([this.props.height, 0]);
},
componentWillUpdate: function() {
var context = this.refs.canvas.getContext('2d');
context.clearRect(0, 0, this.props.width, this.props.height);
},
drawNodes: function() {
var scaleX = this.scaleX();
var scaleY = this.scaleY();
var color = utils.getColors(3)[1];
var x, y, height;
var width = scaleX(this.state.histData[0].x + this.state.histData[0].dx) - scaleX(this.state.histData[0].x);
return _.map(this.state.histData, function(d, i) {
x = scaleX(d.x);
y = scaleY(d.y);
height = this.props.height - y;
return (React.createElement(Bin, {x: x, y: y, width: width, height: height, color: color, value: d.y, key: i}))
}, this);
},
handleZoom: function(zoom) {
if(!this.props.zoom) {
return;
}
var bins = Math.round(this.state.initialBins * zoom.scale);
bins = Math.min(Math.max(1, bins), 250);
if(bins === this.state.bins) {
return;
}
var histData = d3.layout.histogram().bins(bins)(this.props.values);
this.setState({
bins: bins,
histData: histData
});
},
getTicks: function() {
var ret = this.state.bins;
while(ret > this.props.width / 25) {
ret /= 2;
}
return ret;
},
render: function() {
return (
React.createElement(AxisWrapper, {width: this.props.width, height: this.props.height, scale: this.scaleX(), ticks: this.getTicks(), innerTickSize: 0, onZoomed: this.handleZoom},
React.createElement(Canvas, {ref: "canvas"},
this.drawNodes()
)
)
)
}
});
module.exports = Histogram;
| {
"content_hash": "bd6dfb69c88173beb4b7fba9a26ab519",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 190,
"avg_line_length": 28.439252336448597,
"alnum_prop": 0.5494577719355899,
"repo_name": "lightning-viz/lightning-histogram",
"id": "8a8ad88973ab036b4d69a29e3f9211bc1d3967e6",
"size": "3043",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/components/histogram.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "26045"
},
{
"name": "Python",
"bytes": "126"
},
{
"name": "Scala",
"bytes": "148"
}
],
"symlink_target": ""
} |
/**
* Created by Yosleny Leal on 8/22/14.
*/
Ext.define('Admin.store.GeneralSchedule', {
extend: 'Ext.data.Store',
model: 'Admin.model.GeneralSchedule',
remoteSort: true,
proxy: {
type: 'ajax',
api: {
read: 'admin/get-restaurant-general-schedule'
},
reader: {
type: 'json',
root: 'schedules',
successProperty: 'success',
totalProperty: 'total'
},
autoLoad: true,
pageSize: 25
},
constructor : function(config){
this.callParent([config]);
this.on(
'write',
function(me, opts) {
this.sort(opts);
},
this
);
}
}); | {
"content_hash": "6d3ccfceaaa731e4b1e034d4e2a2763c",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 57,
"avg_line_length": 22.575757575757574,
"alnum_prop": 0.47114093959731546,
"repo_name": "akhilreddyjirra/website",
"id": "a662b0aed862b2a82b9f13b1770de9a8e0f55816",
"size": "745",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/app/store/GeneralSchedule.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "155082"
},
{
"name": "JavaScript",
"bytes": "564507"
},
{
"name": "PHP",
"bytes": "538079"
}
],
"symlink_target": ""
} |
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
version = '0.17'
install_requires = [
'pyramid >=1.6a2',
]
tests_require = [
'pytest',
'WebTest',
'colander',
'jsonschema',
'pyramid_sqlalchemy >=1.2',
'pyramid_tm',
]
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['tests']
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno)
setup(name='rest_toolkit',
version=version,
description='REST toolkit',
long_description=open('README.rst').read() + '\n' +
open('changes.rst').read(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Pyramid',
'Intended Audience :: Developers',
'License :: DFSG approved',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP :: WSGI',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords='REST Pyramid',
author='Wichert Akkerman',
author_email='[email protected]',
url='https://github.com/wichert/rest_toolkit',
license='BSD',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=True,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'tests': tests_require},
cmdclass={'test': PyTest},
)
| {
"content_hash": "dc2d78acfa75967d7274635b79164d23",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 73,
"avg_line_length": 30.176470588235293,
"alnum_prop": 0.5701754385964912,
"repo_name": "wichert/rest_toolkit",
"id": "630bdf1e316dfc98de01d6e6e40aeee2df418efd",
"size": "2052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "51249"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7238907e3591421c691eb373f9d6b95a",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "56408949371225cee16fcf3a12ea9f266079cf4b",
"size": "196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Vitales/Vitaceae/Cissus/Cissus verticillata/Cissus sicyoides paraguayensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>FOS++: hdim::experimental::FOS< T > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="HDIMLogo.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">FOS++
 <span id="projectnumber">0.1</span>
</div>
<div id="projectbrief">FOS in a sensisble implementation language.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classhdim_1_1experimental_1_1_f_o_s.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pro-attribs">Protected Attributes</a> |
<a href="classhdim_1_1experimental_1_1_f_o_s-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">hdim::experimental::FOS< T > Class Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>The <a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html" title="The FOS algorithim. ">FOS</a> algorithim.
<a href="classhdim_1_1experimental_1_1_f_o_s.html#details">More...</a></p>
<p><code>#include <<a class="el" href="x__fos_8h_source.html">x_fos.h</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a5eda0a741a322b5a3f06794f851bf6f9"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html#a5eda0a741a322b5a3f06794f851bf6f9">FOS</a> (const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &x, const Eigen::Matrix< T, Eigen::Dynamic, 1 > &y)</td></tr>
<tr class="memdesc:a5eda0a741a322b5a3f06794f851bf6f9"><td class="mdescLeft"> </td><td class="mdescRight">Initialize a new algorithm, and instantiate member attributes X and Y. <a href="#a5eda0a741a322b5a3f06794f851bf6f9">More...</a><br /></td></tr>
<tr class="separator:a5eda0a741a322b5a3f06794f851bf6f9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0d4abf961468ae1ba517ae37f5b7c05a"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0d4abf961468ae1ba517ae37f5b7c05a"></a>
 </td><td class="memItemRight" valign="bottom"><b>FOS</b> (const <a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html">FOS</a> &rhs)</td></tr>
<tr class="separator:a0d4abf961468ae1ba517ae37f5b7c05a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a855f858855fac80444b8a3f28c61f5c6"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html#a855f858855fac80444b8a3f28c61f5c6">Run</a> ()</td></tr>
<tr class="memdesc:a855f858855fac80444b8a3f28c61f5c6"><td class="mdescLeft"> </td><td class="mdescRight">Run the main X_FOS algorithm. <a href="#a855f858855fac80444b8a3f28c61f5c6">More...</a><br /></td></tr>
<tr class="separator:a855f858855fac80444b8a3f28c61f5c6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a41531194ebe2ed31a7739ae46a6998c5"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a41531194ebe2ed31a7739ae46a6998c5"></a>
Eigen::Matrix< T, 1, Eigen::Dynamic > </td><td class="memItemRight" valign="bottom"><b>ReturnLambdas</b> ()</td></tr>
<tr class="separator:a41531194ebe2ed31a7739ae46a6998c5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac42648f601949cb8d3d8340629a74934"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac42648f601949cb8d3d8340629a74934"></a>
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > </td><td class="memItemRight" valign="bottom"><b>ReturnBetas</b> ()</td></tr>
<tr class="separator:ac42648f601949cb8d3d8340629a74934"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:add1b929cf7937a435c281c5acb9b8272"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="add1b929cf7937a435c281c5acb9b8272"></a>
uint </td><td class="memItemRight" valign="bottom"><b>ReturnOptimIndex</b> ()</td></tr>
<tr class="separator:add1b929cf7937a435c281c5acb9b8272"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af5a83765c9988e9ba3e7229a69986957"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af5a83765c9988e9ba3e7229a69986957"></a>
Eigen::Matrix< T, Eigen::Dynamic, 1 > </td><td class="memItemRight" valign="bottom"><b>ReturnCoefficients</b> ()</td></tr>
<tr class="separator:af5a83765c9988e9ba3e7229a69986957"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a>
Protected Attributes</h2></td></tr>
<tr class="memitem:a4f5c8288b55eb6871d84b29ac4a9e8cf"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4f5c8288b55eb6871d84b29ac4a9e8cf"></a>
Eigen::Matrix< T, Eigen::Dynamic, 1 > </td><td class="memItemRight" valign="bottom"><b>fos_fit</b></td></tr>
<tr class="separator:a4f5c8288b55eb6871d84b29ac4a9e8cf"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab1e5315e92f770aff331bec4e1fc25c5"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab1e5315e92f770aff331bec4e1fc25c5"></a>
Eigen::Matrix< T, Eigen::Dynamic, 1 > </td><td class="memItemRight" valign="bottom"><b>lambdas</b></td></tr>
<tr class="separator:ab1e5315e92f770aff331bec4e1fc25c5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a09fcd2c13f60df9ca8a08520b38e972c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a09fcd2c13f60df9ca8a08520b38e972c"></a>
uint </td><td class="memItemRight" valign="bottom"><b>optim_index</b></td></tr>
<tr class="separator:a09fcd2c13f60df9ca8a08520b38e972c"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><h3>template<typename T><br />
class hdim::experimental::FOS< T ></h3>
<p>The <a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html" title="The FOS algorithim. ">FOS</a> algorithim. </p>
<p>Definition at line <a class="el" href="x__fos_8h_source.html#l00033">33</a> of file <a class="el" href="x__fos_8h_source.html">x_fos.h</a>.</p>
</div><h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a class="anchor" id="a5eda0a741a322b5a3f06794f851bf6f9"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename T > </div>
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html">hdim::experimental::FOS</a>< T >::<a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html">FOS</a> </td>
<td>(</td>
<td class="paramtype">const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > & </td>
<td class="paramname"><em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const Eigen::Matrix< T, Eigen::Dynamic, 1 > & </td>
<td class="paramname"><em>y</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Initialize a new algorithm, and instantiate member attributes X and Y. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">x</td><td>An n x p design matrix</td></tr>
<tr><td class="paramname">y</td><td>An n x 1 vector </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="x__fos_8h_source.html#l00179">179</a> of file <a class="el" href="x__fos_8h_source.html">x_fos.h</a>.</p>
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="a855f858855fac80444b8a3f28c61f5c6"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename T > </div>
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html">hdim::experimental::FOS</a>< T >::Run </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Run the main X_FOS algorithm. </p>
<p>Calling this function will run the X_FOS algorithm using the values of X and Y that were instantiated with the class constructor. </p>
<p>Definition at line <a class="el" href="x__fos_8h_source.html#l00675">675</a> of file <a class="el" href="x__fos_8h_source.html">x_fos.h</a>.</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><b>hdim</b></li><li class="navelem"><b>experimental</b></li><li class="navelem"><a class="el" href="classhdim_1_1experimental_1_1_f_o_s.html">FOS</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "f0864931d422afc4e33340eff2bc0a95",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 400,
"avg_line_length": 55.53909465020576,
"alnum_prop": 0.6689389448725548,
"repo_name": "LedererLab/FOS",
"id": "99066b2083b6b5fe6d67a662ef142b76b99464d3",
"size": "13496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/classhdim_1_1experimental_1_1_f_o_s.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "67103"
},
{
"name": "JavaScript",
"bytes": "723"
},
{
"name": "Python",
"bytes": "7210"
},
{
"name": "QMake",
"bytes": "1688"
},
{
"name": "Shell",
"bytes": "395"
}
],
"symlink_target": ""
} |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:id="@+id/fourPlayerLayout"
tools:context="ualberta15.reflex.FourPlayerActivity">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:text="Player One"
android:textSize="20pt"
android:id="@+id/PlayerOneButton"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:text="Player Two"
android:textSize="20pt"
android:id="@+id/PlayerTwoButton" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:text="Player Three"
android:textSize="20pt"
android:id="@+id/PlayerThreeButton"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:text="Player Four"
android:textSize="20pt"
android:id="@+id/PlayerFourButton" />
</LinearLayout>
| {
"content_hash": "710eda848f6ac86b6b9bfb407d3fc4b6",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 96,
"avg_line_length": 35.02272727272727,
"alnum_prop": 0.6645035691109669,
"repo_name": "Benobi42/bschreib-Reflex",
"id": "929ef7e8c363523c4fc88e1ddd61bcc0fd0d3c83",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_four_player.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "58228"
}
],
"symlink_target": ""
} |
package storage_test
import (
"github.com/DATA-DOG/go-sqlmock"
. "github.com/mantzas/incata/storage"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
var _ = Describe("Storage", func() {
It("execute returns expected data", func() {
dbInner, mock, _ := sqlmock.New()
storage, _ := NewStorageFinalized(dbInner, MSSQL, "Event")
mock.ExpectExec("123").WithArgs(1, 2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
storage.Exec("123", 1, 2, 3)
err := mock.ExpectationsWereMet()
Expect(err).NotTo(HaveOccurred(), "there were unfulfilled expections: %s", err)
})
It("query returns expected data", func() {
dbInner, mock, _ := sqlmock.New()
storage, _ := NewStorageFinalized(dbInner, PostgreSQL, "Event")
var rows *sqlmock.Rows
mock.ExpectQuery("123").WithArgs(1, 2, 3).WillReturnRows(rows)
storage.Query("123", 1, 2, 3)
err := mock.ExpectationsWereMet()
Expect(err).NotTo(HaveOccurred(), "there were unfulfilled expections: %s", err)
})
It("close suceeds", func() {
dbInner, mock, _ := sqlmock.New()
storage, _ := NewStorageFinalized(dbInner, MSSQL, "Event")
mock.ExpectClose()
storage.Close()
err := mock.ExpectationsWereMet()
Expect(err).NotTo(HaveOccurred(), "there were unfulfilled expections: %s", err)
})
It("wrong db type returns error when creating new finalized storage", func() {
dbInner, _, _ := sqlmock.New()
_, err := NewStorageFinalized(dbInner, 3, "Event")
Expect(err).To(HaveOccurred())
})
It("wrong db type returns error when creating new storage", func() {
_, err := NewStorage(3, "123", "Event")
Expect(err).To(HaveOccurred())
})
It("new storage returns error when opening", func() {
_, err := NewStorage(MSSQL, "123", "Event")
Expect(err).To(HaveOccurred())
})
DescribeTable("Convert string to DB type",
func(text string, expectedDbType DbType, hasErrors bool) {
actualDbType, err := ConvertToDbType(text)
if hasErrors {
Expect(err).To(HaveOccurred())
} else {
Expect(actualDbType).To(Equal(expectedDbType))
}
},
Entry("mssql", "mssql", MSSQL, false),
Entry("MSSQL", "MSSQL", MSSQL, false),
Entry("MsSQL", "MsSQL", MSSQL, false),
Entry("MsSql", "MsSql", MSSQL, false),
Entry("postgresql", "postgresql", PostgreSQL, false),
Entry("PostgreSQL", "PostgreSQL", PostgreSQL, false),
Entry("POSTGRESQL", "POSTGRESQL", PostgreSQL, false),
Entry("xxx", "xxx", PostgreSQL, true),
)
})
| {
"content_hash": "a3ae335381973ad98397e19ff4c0de28",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 84,
"avg_line_length": 27.175824175824175,
"alnum_prop": 0.6680145572179539,
"repo_name": "mantzas/incata",
"id": "ca2d8137c60ad76e565bab813f69f931cecff2dc",
"size": "2473",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "storage/storage_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "26974"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?>
<DynamicTimeIndexedProblemConfig>
<AnalyticDDPSolver Name="ADDP">
<Debug>0</Debug>
<MaxIterations>500</MaxIterations>
<FunctionTolerance>1e-5</FunctionTolerance>
<GradientTolerance>1e-5</GradientTolerance>
<GradientToleranceConvergenceThreshold>1e-5</GradientToleranceConvergenceThreshold>
<ClampControlsInForwardPass>1</ClampControlsInForwardPass>
<RegularizationRate>1e-1</RegularizationRate>
</AnalyticDDPSolver>
<DynamicTimeIndexedShootingProblem Name="cartpole">
<LossType>Huber</LossType>
<HuberRate>1e-3</HuberRate>
<ControlCostWeight>25</ControlCostWeight>
<R_rate>0</R_rate>
<PlanningScene>
<Scene>
<JointGroup>actuated_joints</JointGroup>
<!-- Noetic compatibility changes: -->
<URDF>{exotica_cartpole_dynamics_solver}/resources/cartpole.urdf</URDF>
<SRDF>{exotica_cartpole_dynamics_solver}/resources/cartpole.srdf</SRDF>
<SetRobotDescriptionRosParams>1</SetRobotDescriptionRosParams>
<DynamicsSolver>
<CartpoleDynamicsSolver Name="solver">
<ControlLimitsLow> -30.0</ControlLimitsLow>
<ControlLimitsHigh> 30.0</ControlLimitsHigh>
<dt>0.01</dt>
</CartpoleDynamicsSolver>
</DynamicsSolver>
</Scene>
</PlanningScene>
<T>200</T>
<tau>0.01</tau>
<Q_rate>0</Q_rate>
<Qf_rate>1e3</Qf_rate>
<StartState>0 0 0 0</StartState>
<GoalState>0 3.1415 0 0</GoalState>
</DynamicTimeIndexedShootingProblem>
</DynamicTimeIndexedProblemConfig>
| {
"content_hash": "e9403396ac1703e54f188a322073c181",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 91,
"avg_line_length": 41.44186046511628,
"alnum_prop": 0.6094276094276094,
"repo_name": "openhumanoids/exotica",
"id": "c17be4e432e91008e51b86089e764f0c4dc1fa8c",
"size": "1782",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "exotica_examples/resources/configs/dynamic_time_indexed/21_sparse_ddp_cartpole.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "790420"
},
{
"name": "C++",
"bytes": "660812"
},
{
"name": "CMake",
"bytes": "24726"
},
{
"name": "Python",
"bytes": "21562"
},
{
"name": "Shell",
"bytes": "1270"
},
{
"name": "TeX",
"bytes": "44880"
}
],
"symlink_target": ""
} |
date: 2018-11-18 14:18:55
title: Apu
tags:
- politics
- india
- quotes
---
From Soutik Biswas', "[_The Simpsons: Not all Indians think Apu is a racist stereotype_](https://www.bbc.com/news/world-asia-india-44027613)"
> "As I see it, there are two primary products that second generation Indian American comedians sell - the ridiculousness of their parents' 'culture' (arranged marriage and 'my son, the doctor' are the commonest tropes); and the racism of white Americans," [Professor Chakravorty](https://sites.temple.edu/sanjoy/), who teaches at Temple University in Pennsylvania, told me in an email interview .
>
> "It is not hard to see why these two lowest hanging fruits are plucked all the time. This is very standard fare. Apu is also very standard fare. What Kondabulu has done is nothing new. He picked almost the most identifiable Indian project possible in the US. And he plugged into the market for identity-based outrage."
and
> "I like Apu, in fact I love him. He has a PhD in computer science, but enjoys running his store, he is a valued citizen of Springfield, a ladies man and adores cricket and is funny," Sidharth Bhatia, Mumbai-based founder-editor of The Wire, told me.
>
> "It reflects true American diversity. The controversy about the stereotyping is classist snobbery - Indians in America don't want to be reminded of a certain kind of immigrant from their country - the shop keepers, the taxi drivers, the burger flippers," says Mr Bhatia.
>
> "They would rather project only Silicon Valley successes, the Wall Street players and the Ivy League products, with the proper accents, people they meet for dinner - by itself a stereotype. The millions of Apus in America, the salt-of-the-earth types, with their less 'posh' accents, are an inconvenience to that self-image of this small group of Indian-Americans."
Bingo.
> His accent apart, Apu is a Midwestern pillar. Would the critics really have him speak like the other characters in the show, as if to say you’re not American unless you sound like someone from Des Moines? Are all caricatured accents racist? Should we ban “foreigners” from comedy shows altogether?
>
> Naturally not—because we wouldn’t, then, have Apu. And can you really imagine America without him?
-- Tunku Varadarajan, [_Leave Apu Alone -- He's a Great American_](https://archive.is/EaQaR)
To quote Lewis Black [entirely out of context](http://www.freedomtomarry.org/blog/entry/voice-for-equality-lewis-black): on a list of priorities, this "is on page six after 'Are we eating too much garlic as a people?'"
| {
"content_hash": "dfb293594300458ed89951f535d4548a",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 397,
"avg_line_length": 83.38709677419355,
"alnum_prop": 0.7659574468085106,
"repo_name": "afreeorange/log",
"id": "9b5afea9296a964e756e644d524d9c7e701220af",
"size": "2599",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "posts/2018/apu.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "19499"
},
{
"name": "Python",
"bytes": "13478"
},
{
"name": "Shell",
"bytes": "852"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.ConcatenateTwoFiles")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.ConcatenateTwoFiles")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a0d61ecd-4279-4b5f-8a64-3379df87cef3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "b322ed6e53103a0d20c4de8447de767a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.361111111111114,
"alnum_prop": 0.7473535638673253,
"repo_name": "PetarMetodiev/Telerik-Homeworks",
"id": "c56b5484bf88def0c528e4d94415f0a60c45683a",
"size": "1420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C# Part 2/06.Text-files/TextFiles/02.ConcatenateTwoFiles/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "861525"
},
{
"name": "CSS",
"bytes": "50847"
},
{
"name": "CoffeeScript",
"bytes": "3700"
},
{
"name": "HTML",
"bytes": "120154"
},
{
"name": "JavaScript",
"bytes": "185461"
}
],
"symlink_target": ""
} |
#include "VariableGroup.h"
#include <QtDebug>
#include <QtXml/QDomElement>
VariableGroup::VariableGroup(const VariableId & sectionId)
: section_id(sectionId)
, csvRows(0)
{
}
/*
VariableGroup::VariableGroup(const QDomElement & de)
{
readXml(de);
}
*/
VariableId VariableGroup::sectionId(void) const
{
return section_id;
}
bool VariableGroup::isEmpty(void) const
{
return var_map.isEmpty();
}
int VariableGroup::size(void) const
{
return var_map.size();
}
bool VariableGroup::contains(const VariableId & id) const
{
return var_map.contains(id.sortable());
}
void VariableGroup::add(const Variable & var)
{
VariableId vid = var.id();
vid.prepend(section_id);
id_list.append(vid);
var_map.insert(vid.sortable(), var);
//qDebug() << objectName() << vid() << "<+" << var.var();
csvRows = qMax(csvRows, var.csvHeadingCount());
}
void VariableGroup::add(VariableGroup * other,
VariableId sectionId)
{
if (sectionId.isNull()) sectionId = other->sectionId();
foreach (Variable v, other->all())
{
VariableId vid(v.id());
vid.prepend(sectionId);
set(vid, v.var());
}
}
Variable VariableGroup::at(const VariableId & id) const
{
Variable v(var_map.value(id.sortable()));
//qDebug() << id() << "@" << v.var();
return v;
}
QVariant VariableGroup::value(const VariableId & id) const
{
return at(id).var();
}
bool VariableGroup::set(const VariableId & id, const Variable & var)
{
bool result = var_map.contains(id.sortable());
if (result)
var_map[id.sortable()] = var;
else
add(var);
//qDebug() << objectName() << id() << "<-" << var.var();
return result;
}
bool VariableGroup::set(const VariableId & id, const QVariant & var)
{
if (var_map.contains(id.sortable()))
{
var_map[id.sortable()].set(var);
//qDebug() << sectionId()() << id() << "<-" << var;
return true;
}
else
{
add(Variable(id, var));
return false;
}
}
void VariableGroup::set(const VariableGroup * vars)
{
foreach (Variable v, vars->all())
set(v.id(), v);
}
int VariableGroup::implant(const VariableId & sectionId,
const VariableGroup * vars)
{
int count = 0;
foreach (Variable v, vars->all())
if (v.id().section(0) == sectionId)
{
VariableId vid = v.id();
QString newId = vid.sections(1);
//qDebug() << newId << "<i" << v.var();
set(VariableId(newId), v.var());
++count;
}
return count;
}
void VariableGroup::reset(const VariableId & id)
{
if (var_map.contains(id.sortable()))
var_map[id.sortable()].reset();
}
void VariableGroup::reset()
{
foreach (QString key, var_map.keys())
var_map[key].reset();
}
void VariableGroup::clear(void)
{
var_map.clear();
id_list.clear();
}
void VariableGroup::remove(const VariableId & id)
{
var_map.remove(id.sortable());
id_list.removeAll(id);
}
VariableIdList VariableGroup::ids(void) const
{
return id_list;
}
QStringList VariableGroup::sectionIds(const VariableId & within)
{
QStringList result;
if (within.isNull())
foreach (VariableId vid, id_list)
{
QString section(vid.section(0));
if ( ! result.contains(section))
result.append(section);
}
else
{
int n = within.sectionCount();
foreach (VariableId vid, id_list)
{
QString section(vid.section(n));
if (QString(within) == vid.sections(0, n-1))
if ( ! result.contains(section))
result.append(section);
}
}
return result;
}
QList<Variable> VariableGroup::all(void) const
{
return var_map.values();
}
void VariableGroup::dump(void) const
{
qDebug() << "Dumping" << sectionId();
foreach (VariableId id, id_list)
{
Variable v = var_map.value(id.sortable());
qDebug() << "---" << id << "=" << v.var();
}
}
/*
QDomElement VariableGroup::writeXml(void) const
{
QDomElement result;
// TODO
return result;
}
bool VariableGroup::readXml(const QDomElement & de)
{
// TODO
return false;
}
*/
int VariableGroup::csvHeadingRowCount(void) const
{
return csvRows;
}
| {
"content_hash": "571ca896ea30f09e6b31fb1855d13ab1",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 68,
"avg_line_length": 21.28780487804878,
"alnum_prop": 0.5847846012832264,
"repo_name": "eirTony/INDI1",
"id": "bf59e60f5a6d779e0197ad0313b6c38a0acdc6f7",
"size": "4364",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/static/INDI2/oldEIRlibs/eirCore/VariableGroup.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2182"
},
{
"name": "C",
"bytes": "987751"
},
{
"name": "C++",
"bytes": "25614243"
},
{
"name": "CMake",
"bytes": "723934"
},
{
"name": "CSS",
"bytes": "175949"
},
{
"name": "Cuda",
"bytes": "311879"
},
{
"name": "HTML",
"bytes": "839417"
},
{
"name": "Java",
"bytes": "127925"
},
{
"name": "JavaScript",
"bytes": "199216"
},
{
"name": "M4",
"bytes": "200"
},
{
"name": "Makefile",
"bytes": "6245411"
},
{
"name": "Mathematica",
"bytes": "284"
},
{
"name": "Objective-C++",
"bytes": "53970"
},
{
"name": "Prolog",
"bytes": "2474"
},
{
"name": "Python",
"bytes": "415039"
},
{
"name": "QMake",
"bytes": "173988"
},
{
"name": "Shell",
"bytes": "3748"
},
{
"name": "TeX",
"bytes": "1530252"
}
],
"symlink_target": ""
} |
Collection Registry & Collection Tags
=====================================
The Collection Registry is a special service that allows you to simplify the code you use to
retrieve multiple collections of the same semantic hierarchy at the same time.
Simple collections
------------------
For example, imagine you have a lot of collections:
.. code-block:: yaml
video_collection:
default:
vm_id: 123
limit: 10
collections:
channel_1:
channel_id: 13264
channel_2:
channel_id: 13265
channel_3:
channel_id: 13266
channel_4:
channel_id: 13267
But you want all of these to appear on the same page below each other, so like:
+---------------+-------------+
| Collection #1 | Videos |
+---------------+-------------+
| Collection #2 | Videos |
+---------------+-------------+
| Collection #3 | Videos |
+---------------+-------------+
| Collection #4 | Videos |
+---------------+-------------+
Your implementation code would look something like this:
.. code-block:: php
<?php
// ...
$collections = [
$container->get('video_collections.collection.channel_1'),
$container->get('video_collections.collection.channel_2'),
$container->get('video_collections.collection.channel_3'),
$container->get('video_collections.collection.channel_4'),
];
foreach ($collections as $collection) {
// Draw the table
}
This is bad, because effectively you statically name all of your collections twice, and if you were
to rename them in the configuration, you would have to rename them in the code as well.
Using the service ``@video_collections.registry`` you can simplify the example above to this:
.. code-block:: php
<?php
// ...
$registry = $container->get('video_collections.registry');
foreach ($registry->getAll() as $collection) {
// Draw the table
}
Tagged Collections
------------------
Now imagine your business logic is a little bit more complicated and you want the following:
But you want all of these to appear on the same page below each other, so like:
+---------------+-------------+
| Featured #1 | Videos |
+---------------+-------------+
| Featured #2 | Videos |
+---------------+-------------+
| Collection #1 | Videos |
+---------------+-------------+
| Collection #2 | Videos |
+---------------+-------------+
| Collection #3 | Videos |
+---------------+-------------+
| Collection #4 | Videos |
+---------------+-------------+
You have two collections of featured videos that you want displayed at the top, and an undefined
amount of collections below that. You can use **collection tags** for this:
.. code-block:: yaml
video_collection:
default:
vm_id: 123
limit: 10
collections:
featured_1:
channel_id: 13264
search_term: true
search_field: featured
tags: [featured]
featured_2:
channel_id: 13264
search_term: true
search_field: featured
tags: [featured]
channel_1:
channel_id: 13264
tags: [other]
channel_2:
channel_id: 13265
tags: [other]
channel_3:
channel_id: 13266
tags: [other]
channel_4:
channel_id: 13267
tags: [other]
Using the ``tags`` parameter in the collection definition, you can group video collections and in your
code retrieve them by tag:
.. code-block:: php
<?php
// ...
$registry = $container->get('video_collections.registry');
foreach ($registry->getByTag('featured') as $collection) {
// Draw the featured videos at the top of the table
}
foreach ($registry->getByTag('other') as $collection) {
// Draw the featured videos at the top of the table
}
Each collection can have multiple tags, so you can make it as flexible as you'd like. | {
"content_hash": "5cd85b5a8760ea29404c97372d8471e4",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 102,
"avg_line_length": 28.28187919463087,
"alnum_prop": 0.5306122448979592,
"repo_name": "MovingImage24/VideoCollectionBundle",
"id": "3b37e99a712d34e04ca843dff190b8541a8d0873",
"size": "4214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Resources/doc/services/collection_registry.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "21717"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/renstrom/shortuuid)
[](https://godoc.org/github.com/renstrom/shortuuid)
A Go library that generates concise, unambiguous, URL-safe UUIDs. Based on and compatible with the Python library [`shortuuid`](https://github.com/stochastic-technologies/shortuuid).
Often, one needs to use non-sequential IDs in places where users will see them, but the IDs must be as concise and easy to use as possible. shortuuid solves this problem by generating UUIDs using [satori/go.uuid](https://github.com/satori/go.uuid) and then translating them to base57 using lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.
## Usage
```go
package main
import (
"fmt"
"github.com/renstrom/shortuuid"
)
func main() {
u := shortuuid.New() // Cekw67uyMpBGZLRP2HFVbe
}
```
To use UUID v5 (instead of the default v4), use `NewWithNamespace(name string)` instead of `New()`.
```go
shortuuid.NewWithNamespace("http://example.com")
```
It's possible to use a custom alphabet as well, though it has to be 57 characters long.
```go
alphabet := "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxy="
shortuuid.NewWithAlphabet(alphabet) // u=BFWRLr5dXbeWf==iasZi
```
Bring your own encoder! For example, base58 is popular among bitcoin.
```go
package main
import (
"fmt"
"github.com/btcsuite/btcutil/base58"
"github.com/renstrom/shortuuid"
"github.com/satori/go.uuid"
)
type base58Encoder struct {}
func (enc base58Encoder) Encode(u uuid.UUID) string {
return base58.Encode(u.Bytes())
}
func (enc base58Encoder) Decode(s string) (uuid.UUID, error) {
return uuid.FromBytes(base58.Decode(s))
}
func main() {
enc := base58Encoder{}
fmt.Println(shortuuid.NewWithEncoder(enc)) // 6R7VqaQHbzC1xwA5UueGe6
}
```
## License
MIT
| {
"content_hash": "daba6bff789ed51cda4771fd039de0a6",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 399,
"avg_line_length": 29.83582089552239,
"alnum_prop": 0.7378689344672336,
"repo_name": "lewgun/argyroneta",
"id": "1f4351c5a3f0b51aa93ca536231b29475d623c34",
"size": "2012",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/renstrom/shortuuid/README.md",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "31227"
}
],
"symlink_target": ""
} |
package org.couchbase.mock.httpio;
import org.apache.http.*;
import org.apache.http.impl.DefaultBHttpServerConnectionFactory;
import org.apache.http.protocol.*;
import org.apache.http.util.VersionInfo;
import org.couchbase.mock.Info;
import java.io.IOException;
import java.net.*;
import java.nio.channels.ServerSocketChannel;
import java.util.HashSet;
import java.util.Set;
public class HttpServer extends Thread {
/**
* Subclass of HttpService which adds some additional hooks to all responses
*/
static class MyHttpService extends HttpService {
MyHttpService(HttpProcessor proc, UriHttpRequestHandlerMapper registry) {
super(proc, registry);
}
@Override
protected void doService(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
response.addHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate"); // Disable caching
// Normalize the URI
super.doService(request, response, context);
}
}
/**
* Subclass of UriHttpRequestHandlerMapper which normalizes a URI and matches only its path.
* This is because we ignore the host part (we don't use the {@code Host} header)
*/
static class MyRequestHandlerMapper extends UriHttpRequestHandlerMapper {
@Override
protected String getRequestPath(final HttpRequest request) {
String s = request.getRequestLine().getUri();
try {
URI uri = new URI(s);
return uri.getPath();
} catch (URISyntaxException ex) {
return s;
} catch (IllegalArgumentException ex) {
return s;
}
}
}
private volatile boolean shouldRun = true;
private final DefaultBHttpServerConnectionFactory connectionFactory;
private final HttpService httpService;
private final UriHttpRequestHandlerMapper registry;
private final Set<Worker> allWorkers = new HashSet<Worker>();
private static final String serverString = String.format("CouchbaseMock/%s (mcd; views) httpcomponents/%s",
Info.getVersion(), VersionInfo.loadVersionInfo("org.apache.http", null).getRelease());
private ServerSocketChannel listener;
final public static String CX_SOCKET = "couchbase.mock.http.socket";
final public static String CX_AUTH = "couchbase.mock.http.auth";
/**
* Creates a new server. To make the server respond to requests, invoke
* the {@link #bind(java.net.InetSocketAddress)} method to make it use a socket,
* and then invoke the {@link #start()} method to start it up in the background.
*
* Use {@link #register(String, org.apache.http.protocol.HttpRequestHandler)} to add
* handlers which respond to various URL paths
*/
public HttpServer() {
this.connectionFactory = new DefaultBHttpServerConnectionFactory();
this.registry = new MyRequestHandlerMapper();
HttpProcessor httpProcessor = HttpProcessorBuilder.create()
.add(new ResponseServer(serverString))
.add(new ResponseContent())
.add(new ResponseConnControl())
.build();
this.httpService = new MyHttpService(httpProcessor, registry);
// Register the unknown handler
register("*", new HttpRequestHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
}
});
}
/**
* Set the server's listening address
* @param address The address the server should listen on
* @throws IOException if a new socket could not be created
* @see {@link #bind(java.nio.channels.ServerSocketChannel)}
*/
public void bind(InetSocketAddress address) throws IOException {
if (listener != null) {
listener.close();
listener = null;
}
listener = ServerSocketChannel.open();
listener.socket().bind(address);
}
/**
* Set the server's listening socket.
* @param newSock An existing listening socket.
* @see {@link #bind(java.net.InetSocketAddress)}
*/
public void bind(ServerSocketChannel newSock) {
listener = newSock;
}
/**
* Register a path with a handler
* @param pattern The path to register
* @param handler The handler to handle the path
* @see {@link org.apache.http.protocol.UriHttpRequestHandlerMapper}
*/
public void register(String pattern, HttpRequestHandler handler) {
registry.register(pattern, handler);
registry.register(pattern + "/", handler);
}
/**
* Unregister a given path. Further requests to paths matching the specified
* pattern will result in a 404 being delivered to the client
* @param pattern The pattern to unregister. Must have previously been registered
* via {@link #register(String, org.apache.http.protocol.HttpRequestHandler)}
*/
public void unregister(String pattern) {
registry.unregister(pattern);
registry.unregister(pattern + "/");
}
class Worker extends Thread {
final HttpServerConnection htConn;
final Socket rawSocket;
private volatile boolean closeRequested = false;
Worker(HttpServerConnection htConn, Socket rawSocket) {
this.htConn = htConn;
this.rawSocket = rawSocket;
setName("Mock Http Worker: " + rawSocket.getRemoteSocketAddress());
}
void stopSocket() {
closeRequested = true;
try {
this.rawSocket.close();
} catch (IOException ex) {
//
}
}
private void bail() {
this.stopSocket();
}
public void doReadLoop() {
HttpContext context = new BasicHttpContext();
context.setAttribute(CX_SOCKET, rawSocket);
while (!Thread.interrupted() && this.htConn.isOpen() && HttpServer.this.shouldRun) {
// Clear the context from any auth settings; since this is done
// anew on each connection..
context.removeAttribute(CX_AUTH);
try {
HttpServer.this.httpService.handleRequest(htConn, context);
} catch (ConnectionClosedException ex_closed) {
break;
} catch (IOException ex) {
if (!closeRequested) {
ex.printStackTrace();
}
break;
} catch (HttpException ex) {
ex.printStackTrace();
break;
} catch (ResponseHandledException ex) {
break;
}
}
bail();
}
@Override
public void run() {
try {
doReadLoop();
} finally {
synchronized (HttpServer.this.allWorkers) {
HttpServer.this.allWorkers.remove(this);
}
bail();
}
}
}
@Override
public void run() {
setName("Mock HTTP Listener: "+listener.socket().getInetAddress());
while (shouldRun) {
Socket incoming;
try {
incoming = listener.accept().socket();
HttpServerConnection conn = connectionFactory.createConnection(incoming);
Worker worker = new Worker(conn, incoming);
synchronized (allWorkers) {
allWorkers.add(worker);
}
worker.start();
} catch (IOException ex) {
if (shouldRun) {
ex.printStackTrace();
}
}
}
}
/**
* Shut down the HTTP server and all its workers, and close the listener socket.
*/
public void stopServer() {
shouldRun = false;
try {
listener.close();
} catch (IOException ex) {
// Don't care
}
while (true) {
synchronized (allWorkers) {
if (allWorkers.isEmpty()) {
break;
}
for (Worker w : allWorkers) {
w.stopSocket();
w.interrupt();
}
}
}
try {
listener.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| {
"content_hash": "e765f71e2330675b20afa58ce467072a",
"timestamp": "",
"source": "github",
"line_count": 255,
"max_line_length": 133,
"avg_line_length": 34.31764705882353,
"alnum_prop": 0.5795909038966975,
"repo_name": "Playtika/CouchbaseMock",
"id": "24980c72cb457038d3534981530bd5288bc0395e",
"size": "8751",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/main/java/org/couchbase/mock/httpio/HttpServer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "672318"
},
{
"name": "JavaScript",
"bytes": "15624"
}
],
"symlink_target": ""
} |
<?php
namespace WilliamEspindola\Field\Console\Command\Database;
use WilliamEspindola\Field\Storage\ORM\Doctrine;
use Doctrine\ORM\Tools\Setup;
class DoctrineStorage
{
protected $mapper;
const XML_CONFIG_ORM = '/../../../../config/xml/';
public function __construct($config)
{
$setUp = Setup::createXMLMetadataConfiguration([__DIR__ . self::XML_CONFIG_ORM], true);
$this->mapper = new Doctrine($config, $setUp);
}
public function getMapperInstance()
{
return $this->mapper;
}
public function getExecuteQuery($query)
{
$stmt = $this->mapper->getMapper()->getConnection()->prepare($query);
return $stmt->execute();
}
} | {
"content_hash": "7af03aab9953e0f0569a74fc472536d1",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 95,
"avg_line_length": 22.1875,
"alnum_prop": 0.6366197183098592,
"repo_name": "williamespindola/field",
"id": "6fe36de3969b0888946326ed6c741e86932dba51",
"size": "710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Console/Command/Database/DoctrineStorage.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Cucumber",
"bytes": "335"
},
{
"name": "PHP",
"bytes": "54938"
}
],
"symlink_target": ""
} |
import re
from operator import itemgetter
import pytest
from nb_gen.doc_tables import (
get_desc_and_params,
get_input_table_lines,
get_output_table_lines,
)
from pybatfish.client.session import Session
from pybatfish.datamodel.answer.table import ColumnMetadata
@pytest.fixture(scope="module")
def session() -> Session:
return Session()
def test_parameter_extraction(session: Session):
"""Test that we extract parameter info from QuestionMeta classes correctly"""
_, _, params = get_desc_and_params(session.q.nodeProperties)
params = sorted(params, key=itemgetter(0))
assert len(params) == 2
name, pdict = params[0]
assert name == "nodes"
assert pdict["type"] == "nodeSpec"
assert pdict["optional"]
name, pdict = params[1]
assert name == "properties"
assert pdict["type"] == "nodePropertySpec"
assert pdict["optional"]
def test_get_input_table_lines(session: Session):
lines = get_input_table_lines(
get_desc_and_params(session.q.nodeProperties)[2], "nodeProperties"
)
# skip first two lines, markdown header
assert re.match(r"nodes |[\w\s]+|nodeSpec|True|", lines[2])
assert re.match(r"properties |[\w\s]+|nodeSpec|True|", lines[3])
def test_get_output_table_lines():
lines = get_output_table_lines(
[ColumnMetadata(dict(name="Column", description="Dear Abby", schema="String"))],
"qname",
)
assert lines[2] == "Column | Dear Abby | str"
| {
"content_hash": "5cf454ef1aea704c6a1999eb49e26e23",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 88,
"avg_line_length": 29.42,
"alnum_prop": 0.6770904146838885,
"repo_name": "batfish/pybatfish",
"id": "4d8e89bf0ceee31edf9dccf39e2ddfc37cf08f3f",
"size": "1487",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/nb_gen_tests/test_doc_tablen_gen.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "1219681"
},
{
"name": "Python",
"bytes": "684750"
}
],
"symlink_target": ""
} |
/*$Id$*/
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Margo Seltzer.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 EVENT SHALL THE REGENTS 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.
*
* @(#)page.h 8.1 (Berkeley) 6/6/93
*/
/*
* Definitions for hashing page file format.
*/
/*
* routines dealing with a data page
*
* page format:
* +------------------------------+
* p | n | keyoff | datoff | keyoff |
* +------------+--------+--------+
* | datoff | free | ptr | --> |
* +--------+---------------------+
* | F R E E A R E A |
* +--------------+---------------+
* | <---- - - - | data |
* +--------+-----+----+----------+
* | key | data | key |
* +--------+----------+----------+
*
* Pointer to the free space is always: p[p[0] + 2]
* Amount of free space on the page is: p[p[0] + 1]
*/
/*
* How many bytes required for this pair?
* 2 shorts in the table at the top of the page + room for the
* key and room for the data
*
* We prohibit entering a pair on a page unless there is also room to append
* an overflow page. The reason for this it that you can get in a situation
* where a single key/data pair fits on a page, but you can't append an
* overflow page and later you'd have to split the key/data and handle like
* a big pair.
* You might as well do this up front.
*/
#define PAIRSIZE(K,D) (2*sizeof(u_short) + (K)->size + (D)->size)
#define BIGOVERHEAD (4*sizeof(u_short))
#define KEYSIZE(K) (4*sizeof(u_short) + (K)->size);
#define OVFLSIZE (2*sizeof(u_short))
#define FREESPACE(P) ((P)[(P)[0]+1])
#define OFFSET(P) ((P)[(P)[0]+2])
#define PAIRFITS(P,K,D) \
(((P)[2] >= REAL_KEY) && \
(PAIRSIZE((K),(D)) + OVFLSIZE) <= FREESPACE((P)))
#define PAGE_META(N) (((N)+3) * sizeof(u_short))
typedef struct {
BUFHEAD *newp;
BUFHEAD *oldp;
BUFHEAD *nextp;
u_short next_addr;
} SPLIT_RETURN;
| {
"content_hash": "99c404ea085a0471a4ae1ac798987811",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 77,
"avg_line_length": 38.913978494623656,
"alnum_prop": 0.6526664824537165,
"repo_name": "rangsimanketkaew/NWChem",
"id": "6cab7e9a43c4b056d3ddde7a767709973ad07b6d",
"size": "3619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/rtdb/db/page.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "67582"
}
],
"symlink_target": ""
} |
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>wide background-size: auto 32px; for nonpercent-width-omitted-height-viewbox.svg</title>
<link rel="author" title="Jeff Walden" href="http://whereswalden.com/" />
<link rel="help" href="http://www.w3.org/TR/css3-background/#the-background-size" />
<link rel="help" href="http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing" />
<link rel="help" href="http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute" />
<link rel="help" href="http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute" />
<meta name="flags" content="svg" />
<style type="text/css">
div
{
width: 768px; height: 256px;
}
#outer
{
border: 1px solid black;
}
#inner
{
background-image: url(nonpercent-width-omitted-height-viewbox.svg);
background-repeat: no-repeat;
background-size: auto 32px;
}
</style>
</head>
<body>
<div id="outer"><div id="inner"></div></div>
</body>
</html>
| {
"content_hash": "8498e896a448dbdabe5fe371a8f9d4c4",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 97,
"avg_line_length": 29.714285714285715,
"alnum_prop": 0.6855769230769231,
"repo_name": "sergecodd/FireFox-OS",
"id": "4573e583a289835de6d4ec79228ebcda27f2de3c",
"size": "1040",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "B2G/gecko/layout/reftests/backgrounds/vector/wide--auto-32px--nonpercent-width-omitted-height-viewbox.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "443"
},
{
"name": "ApacheConf",
"bytes": "85"
},
{
"name": "Assembly",
"bytes": "5123438"
},
{
"name": "Awk",
"bytes": "46481"
},
{
"name": "Batchfile",
"bytes": "56250"
},
{
"name": "C",
"bytes": "101720951"
},
{
"name": "C#",
"bytes": "38531"
},
{
"name": "C++",
"bytes": "148896543"
},
{
"name": "CMake",
"bytes": "23541"
},
{
"name": "CSS",
"bytes": "2758664"
},
{
"name": "DIGITAL Command Language",
"bytes": "56757"
},
{
"name": "Emacs Lisp",
"bytes": "12694"
},
{
"name": "Erlang",
"bytes": "889"
},
{
"name": "FLUX",
"bytes": "34449"
},
{
"name": "GLSL",
"bytes": "26344"
},
{
"name": "Gnuplot",
"bytes": "710"
},
{
"name": "Groff",
"bytes": "447012"
},
{
"name": "HTML",
"bytes": "43343468"
},
{
"name": "IDL",
"bytes": "1455122"
},
{
"name": "Java",
"bytes": "43261012"
},
{
"name": "JavaScript",
"bytes": "46646658"
},
{
"name": "Lex",
"bytes": "38358"
},
{
"name": "Logos",
"bytes": "21054"
},
{
"name": "Makefile",
"bytes": "2733844"
},
{
"name": "Matlab",
"bytes": "67316"
},
{
"name": "Max",
"bytes": "3698"
},
{
"name": "NSIS",
"bytes": "421625"
},
{
"name": "Objective-C",
"bytes": "877657"
},
{
"name": "Objective-C++",
"bytes": "737713"
},
{
"name": "PHP",
"bytes": "17415"
},
{
"name": "Pascal",
"bytes": "6780"
},
{
"name": "Perl",
"bytes": "1153180"
},
{
"name": "Perl6",
"bytes": "1255"
},
{
"name": "PostScript",
"bytes": "1139"
},
{
"name": "PowerShell",
"bytes": "8252"
},
{
"name": "Protocol Buffer",
"bytes": "26553"
},
{
"name": "Python",
"bytes": "8453201"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3481"
},
{
"name": "Ruby",
"bytes": "5116"
},
{
"name": "Scilab",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "3383832"
},
{
"name": "SourcePawn",
"bytes": "23661"
},
{
"name": "TeX",
"bytes": "879606"
},
{
"name": "WebIDL",
"bytes": "1902"
},
{
"name": "XSLT",
"bytes": "13134"
},
{
"name": "Yacc",
"bytes": "112744"
}
],
"symlink_target": ""
} |
<?php
namespace Hydrogen\Console;
//use
use Hydrogen\Load\Autoloader;
use Hydrogen\Load\Loader;
use Hydrogen\Console\Exception\ClassNotDefinedException;
class ConsoleHelper
{
public $path = '';
public $baseNamespace = '';
public static $_callable_param_prefix = '--';
public function __construct($namespace, $console_path)
{
$this->baseNamespace = $namespace;
$this->path = $console_path;
}
/**
* get callable module list
*
* @return array
*/
public function getCallableModules()
{
$dirIterator = new \RecursiveDirectoryIterator($this->path,
\FilesystemIterator::NEW_CURRENT_AND_KEY|\FilesystemIterator::SKIP_DOTS);
$modules = array();
foreach ($dirIterator as $k => $v) {
$doVotedModule = false;
if ($dirIterator->hasChildren()) {
foreach ($dirIterator->getChildren() as $key => $value) {
$entension = $value->getExtension();
if (!$entension || 'php' !== $entension) {
continue;
}
$fileBasename = $value->getBasename('.php');
$module_to_be = $v->getBasename();
$expectedClassName = $this->baseNamespace.NAMESPACE_SEPARATOR
.$module_to_be.NAMESPACE_SEPARATOR.$fileBasename;
Loader::import($value->__toString());
if (!class_exists($expectedClassName, false)) { // not a standard class file!
continue;
}
if (!$doVotedModule) {
$modules[] = $module_to_be;
$doVotedModule = true;
}
}
}
}
return $modules;
}
/**
* get callable methods within the classObj
*
* @param string|object $classObj
* @param int $filter
* @param bool $filterOwn
* @return array array of \ReflectionMethod
*/
public function getCallableMethods($classObj, $filter, $filterOwn = true)
{
if (is_string($classObj) && !class_exists($classObj, false))
throw new ClassNotDefinedException('Class name: '.$classObj.' not defined yet!');
$className = $classObj;
if (is_object($classObj))
$className = get_class($classObj);
$reflectClass = new \ReflectionClass($classObj);
$methods = array();
if (!$reflectClass->isUserDefined() || !$reflectClass->isInstantiable())
return $methods;
$methods = $reflectClass->getMethods($filter);
if ($filterOwn) {
$needNeaten = false;
foreach ($methods as $k => $method) {
if ($method->class != $className) {
unset($methods[$k]);
!$needNeaten && $needNeaten = true;
}
}
$needNeaten && $methods = array_values($methods);
}
return $methods;
}
/**
* @param string|object $classObj
* @param string $methodName
* @return boolean|int
*/
public function getRequiredMethodArgsCount($classObj, $methodName)
{
$reflectClass = new \ReflectionClass($classObj);
try {
$reflectMethod = $reflectClass->getMethod($methodName);
return $reflectMethod->getNumberOfRequiredParameters();
} catch (\ReflectionException $e) {
return false;
}
}
/**
* @param string|object $classObj
* @param string $methodName
* @return boolean|array
*/
public function getRequiredMethodArgs($classObj, $methodName)
{
$reflectClass = new \ReflectionClass($classObj);
$requiredMethodsArgs = array();
try {
$reflectParams = $reflectClass->getMethod($methodName)->getParameters();
foreach ($reflectParams as $reflectParam) {
/*if ($reflectParam->is) {
}*/
// $requiredMethodsArgs =
}
} catch (\ReflectionException $e) {
return false;
}
}
/**
* extra param for calling user function
*
* @param $argvs
* @return array
*/
public function extractCallableParams($argvs)
{
if (!is_array($argvs)) {
$argvs = array($argvs);
}
$params = array();
$cursor = 0;
foreach ($argvs as $argPos => $argv) {
if (0 === strpos($argv, self::$_callable_param_prefix)) {
$pair = str_replace(self::$_callable_param_prefix, '', $argv);
if (isset($argvs[$argPos + 1])) {
$params[$pair] = $argvs[$argPos + 1];
} else {
$params[$pair] = null;
}
$cursor = $argPos + 1;
if ($argPos <= $cursor) {
continue;
}
}
}
return $params;
}
} | {
"content_hash": "64191f93da31247f7c43d4c109b166a1",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 97,
"avg_line_length": 28.082872928176794,
"alnum_prop": 0.5054101908321857,
"repo_name": "TF-Joynic/Hydrogen",
"id": "770fd0bc01af9de2439507ffd3bada77ee498803",
"size": "5083",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Hydrogen/Console/ConsoleHelper.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "146"
},
{
"name": "HTML",
"bytes": "553"
},
{
"name": "PHP",
"bytes": "374853"
},
{
"name": "Shell",
"bytes": "107"
},
{
"name": "Smarty",
"bytes": "24"
}
],
"symlink_target": ""
} |
namespace Project2GUI
{
partial class MovieBoxMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainPanel = new System.Windows.Forms.FlowLayoutPanel();
this.txtMovieInfo = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// mainPanel
//
this.mainPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.mainPanel.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.mainPanel.Location = new System.Drawing.Point(1, 23);
this.mainPanel.Name = "mainPanel";
this.mainPanel.Size = new System.Drawing.Size(1048, 275);
this.mainPanel.TabIndex = 0;
//
// txtMovieInfo
//
this.txtMovieInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtMovieInfo.BackColor = System.Drawing.Color.Black;
this.txtMovieInfo.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtMovieInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtMovieInfo.ForeColor = System.Drawing.Color.White;
this.txtMovieInfo.Location = new System.Drawing.Point(12, 304);
this.txtMovieInfo.Multiline = true;
this.txtMovieInfo.Name = "txtMovieInfo";
this.txtMovieInfo.Size = new System.Drawing.Size(1022, 49);
this.txtMovieInfo.TabIndex = 10;
this.txtMovieInfo.Text = "Hello World";
//
// MovieBoxMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(1046, 359);
this.Controls.Add(this.txtMovieInfo);
this.Controls.Add(this.mainPanel);
this.Name = "MovieBoxMain";
this.Text = "MovieBoxMain";
this.Load += new System.EventHandler(this.MovieBoxMain_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.FlowLayoutPanel mainPanel;
private System.Windows.Forms.TextBox txtMovieInfo;
}
} | {
"content_hash": "0ca887d564df575e7c0c367f6d7d4876",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 172,
"avg_line_length": 45.09756097560975,
"alnum_prop": 0.5857220118983234,
"repo_name": "majorsilence/MediaService",
"id": "3a7d574e9e116cb99bc864cb53886baaee94a661",
"size": "3700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Majorsilence.MediaService.Client/WinGui/MovieBoxMain.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "82351"
},
{
"name": "PHP",
"bytes": "5654"
}
],
"symlink_target": ""
} |
<?php
namespace Hifone\Http\Controllers\Dashboard;
use AltThree\Validator\ValidationException;
use Hifone\Hashing\PasswordHasher;
use Hifone\Http\Controllers\Controller;
use Hifone\Models\Role;
use Hifone\Models\User;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
use Input;
class UserController extends Controller
{
/**
* Creates a new node controller instance.
*
* @return void
*/
public function __construct(PasswordHasher $hasher)
{
$this->hasher = $hasher;
View::share([
'current_menu' => 'nodes',
'sub_title' => trans_choice('dashboard.nodes.nodes', 2),
]);
}
/**
* Shows the users view.
*
* @return \Illuminate\View\View
*/
public function index()
{
$q = Input::query('q');
$users = User::orderBy('created_at', 'desc')->search($q)->paginate(10);
$roles = Role::all();
return View::make('dashboard.users.index')
->withPageTitle(trans('dashboard.users.users') . ' - ' . trans('dashboard.dashboard'))
->withUsers($users)
->withRoles($roles);
}
/**
* Shows the create user view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return View::make('dashboard.users.create_edit')
->withPageTitle(trans('dashboard.users.add.title') . ' - ' . trans('dashboard.dashboard'));
}
/**
* Stores a new user.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store()
{
$userData = Input::get('user');
$userData['salt'] = str_random(16);
$userData['password'] = $this->hasher->make($userData['password'], ['salt' => $userData['salt']]);
try {
User::create($userData);
} catch (ValidationException $e) {
return Redirect::route('dashboard.user.create')
->withInput(Input::get('user'))
->withTitle(sprintf('%s %s', trans('hifone.whoops'), trans('dashboard.users.add.failure')))
->withErrors($e->getMessageBag());
}
return Redirect::route('dashboard.user.index')
->withSuccess(sprintf('%s %s', trans('hifone.awesome'), trans('dashboard.users.add.success')));
}
public function edit(User $user)
{
$this->subMenu['users']['active'] = true;
return View::make('dashboard.users.create_edit')
->withPageTitle(trans('dashboard.users.add.title') . ' - ' . trans('dashboard.dashboard'))
->withUser($user)
->withSubMenu($this->subMenu);
}
public function update(User $user)
{
$userData = Input::get('user');
if ($userData['password']) {
$userData['salt'] = str_random(6);
$userData['password'] = $this->hasher->make($userData['password'], ['salt' => $userData['salt']]);
} else {
unset($userData['password']);
}
try {
$user->update($userData);
} catch (ValidationException $e) {
return Redirect::route('dashboard.user.edit', ['id' => $user->id])
->withInput(Input::except('password'))
->withTitle(sprintf('%s %s', trans('hifone.whoops'), trans('dashboard.users.edit.failure')))
->withErrors($e->getMessageBag());
}
return Redirect::route('dashboard.user.edit', ['id' => $user->id])
->withSuccess(sprintf('%s %s', trans('hifone.awesome'), trans('dashboard.users.edit.success')));
}
}
| {
"content_hash": "091776bb66fd915778f2435cbbdf6ded",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 110,
"avg_line_length": 31.17241379310345,
"alnum_prop": 0.5611172566371682,
"repo_name": "underdogg-forks/hifone",
"id": "a257eee0bc91010ceb4dfeb0476be0f086ce1113",
"size": "3825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Http/Controllers/Dashboard/UserController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "59542"
},
{
"name": "CoffeeScript",
"bytes": "32650"
},
{
"name": "HTML",
"bytes": "216082"
},
{
"name": "JavaScript",
"bytes": "3171"
},
{
"name": "PHP",
"bytes": "771288"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>junior</artifactId>
<groupId>ru.job4j</groupId>
<version>2.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter_004</artifactId>
</project> | {
"content_hash": "5ba202aa8bb0b421d7e498e4905b8031",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 108,
"avg_line_length": 40.5,
"alnum_prop": 0.6440329218106996,
"repo_name": "ZubovVP/ZubovVP",
"id": "c8a1ce0fd0aa31a1f2ec2775498f41ccc345bc62",
"size": "486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_004/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "21857"
},
{
"name": "Java",
"bytes": "684089"
},
{
"name": "TSQL",
"bytes": "1638"
}
],
"symlink_target": ""
} |
/**
*
*/
function SMSReceivingTask() {
this.id = "SMS Receiving 00"; // top left corner X
this.name = "SMS Receiving"; // top left corner Y
this.x0 = 0; // top left corner X
this.y0 = 0; // top left corner Y
this.x1 = 0; // bottom right corner X
this.y1 = 0; // bottom right corner X
this.status = 0; //
this.description = null;
this.isParallelInput = 0; // 0:no; 1:yes
this.isParallelOutput = 0; // 0:no; 1:yes
this.currOwner = null; // process
this.owner = null; //organization
this.inputs = []; // input transitions (arcs)
this.outputs = []; // output transitions (arcs)
this.marks = []; // eight corner marks
this.classtypename = "SMSReceivingTask";
this.lastupdate = null;
};
SMSReceivingTask.prototype = new AbstractTask();
SMSReceivingTask.prototype.clone = function() {
var a = new SMSReceivingTask();
a.id = this.id;
a.name = this.name;
a.x0 = this.x0; // top left corner X
a.y0 = this.y0; // top left corner Y
a.x1 = this.x1; // bottom right corner X
a.y1 = this.y1; // bottom right corner X
a.selected = this.selected; // is selected on canvas
return a;
};
SMSReceivingTask.prototype.stringifyforJSON = function() {
var a = new SMSReceivingTask();
a.id = this.id;
a.name = this.name;
a.x0 = this.x0; // top left corner X
a.y0 = this.y0; // top left corner Y
a.x1 = this.x1; // bottom right corner X
a.y1 = this.y1; // bottom right corner X
a.description = this.description;
a.isParallelInput = this.isParallelInput;
a.isParallelOutput = this.isParallelOutput;
a.lastupdate = this.lastupdate;
a.currOwner = this.currOwner; // process ID
a.owner = this.owner; // organization ID
return a;
};
SMSReceivingTask.prototype.parse = function(json) {
this.id = json.id;
this.name = json.name;
this.x0 = json.x0; // top left corner X
this.y0 = json.y0; // top left corner Y
this.x1 = json.x1; // bottom right corner X
this.y1 = json.y1; // bottom right corner X
this.description = json.description;
this.isParallelOutput = json.isParallelOutput;
this.isParallelInput = json.isParallelInput;
this.lastupdate = Utils.getDateTime(json.lastupdate)
this.currOwner = json.currOwner; // process ID
this.owner = json.owner; // organization ID
};
//A function for drawing the particle.
SMSReceivingTask.prototype.drawToContext = function() {
var tmp = this.context.fillStyle;
var tmp1 = this.context.strokeStyle;
var cornerRadius = 8;
this.context.beginPath();
this.context.moveTo(this.x0 + cornerRadius, this.y0);
this.context.lineTo(this.x1 - cornerRadius, this.y0);
this.context.arcTo(this.x1, this.y0, this.x1, this.y0 + cornerRadius,
cornerRadius);
this.context.lineTo(this.x1, this.y1 - cornerRadius);
this.context.arcTo(this.x1, this.y1, this.x1 - cornerRadius, this.y1,
cornerRadius);
this.context.lineTo(this.x0 + cornerRadius, this.y1);
this.context.arcTo(this.x0, this.y1, this.x0, this.y1 - cornerRadius,
cornerRadius);
this.context.lineTo(this.x0, this.y0 + cornerRadius);
this.context.arcTo(this.x0, this.y0, this.x0 + cornerRadius, this.y0,
cornerRadius);
this.context.closePath();
this.context.fillStyle = 'rgb(244, 250, 255)';
this.context.fill();
this.context.strokeStyle = 'rgb(196, 210, 237)';
this.context.stroke();
this.context.moveTo(this.x0 + 1, this.y0 + 30);
this.context.lineTo(this.x1 - 1, this.y0 + 30);
this.context.stroke();
this.context.fillStyle = tmp;
this.context.strokeStyle = tmp1; // resume old color
BuildTimeUtils.mobile48x48Receiving(this.context, this.x1 - 48, this.y1 - 48);
var label = new TaskTextLabel(this.x0, this.y0, this.x1, this.y1, this.context);
label.outputText(this.name, "C");
var label1 = new TaskTextLabel(this.x0, this.y0+30, this.x1, this.y1, this.context);
label1.outputText(this.description, "C");
this.marks = Utils.createMarks(this.x0, this.y0, this.x1, this.y1);
if (this.selected) {
Utils.drawSelection(this.marks, this.context);
}
};
SMSReceivingTask.prototype.isInMark = function(x, y) {
if (this.marks != null && this.marks.length > 0) {
for (var i = 0; i < this.marks.length; i++) {
if (this.marks[i].x0 - 4 <= x
&& x <= this.marks[i].x0 + this.marks[i].width + 4
&& this.marks[i].y0 - 4 <= y
&& y <= this.marks[i].y0 + this.marks[i].height + 4) {
return this.marks[i].name;
}
}
}
return "default";
}; | {
"content_hash": "e24436c18bcefc4ed01dd0b1ffe7a241",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 85,
"avg_line_length": 33.44186046511628,
"alnum_prop": 0.6866017617060732,
"repo_name": "CloudBPM/SwinFlowCloud-CloudSide",
"id": "ed4c89b896e20666e6b522fd0574041f6cb50061",
"size": "4314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pm/src/main/webapp/js/tasks/smsreceiving.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
<title>Booking - BlushUp</title>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body>
<nav class="white" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="index.html" class="brand-logo">Logo</a>
<ul class="right hide-on-med-and-down">
<li><a href="booking.html">BOOKING</a></li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li><a href="booking.html">BOOKING</a></li>
</ul>
<a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
</div>
</nav>
<div id="index-banner" class="parallax-container">
<div class="section no-pad-bot">
<div class="container">
<br><br>
<h1 class="header center teal-text text-lighten-2">Parallax Template</h1>
<div class="row center">
<h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5>
</div>
<div class="row center">
<a href="http://materializecss.com/getting-started.html" id="download-button" class="btn-large waves-effect waves-light teal lighten-1">Get Started</a>
</div>
<br><br>
</div>
</div>
<div class="parallax"><img src="images/background1.jpg" alt="Unsplashed background img 1"></div>
</div>
<div class="container">
<div class="section">
<!-- Artist Listing -->
<div class="row">
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image">
<img src="images/kittychong.jpg">
<span class="card-title">Kitty Chong</span>
</div>
<div class="card-content">
<p>As a Makeup Artist (MUA), I hold that ideal imaging of a female is
achieved by exuding her innate beauty and external style in the best light.
Service area within Malaysia.</p>
</div>
<div class="card-action">
<a href="#">Write Review</a>
<a href="#">Book Artist</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="images/kittychong.jpg">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Kitty Chong<i class="material-icons right">more_vert</i></span>
<p>
<a href="#">Write Review</a>
<a href="#">Book Artist</a>
</p>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Kitty Chong<i class="material-icons right">close</i></span>
<p>As a Makeup Artist (MUA), I hold that ideal imaging of a female is achieved
by exuding her innate beauty and external style in the best light.
I focus on delicate makeup enhancing a woman's feature and refining feminity.
Service area within Malaysia.
Price Range: RM 150-300</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 m4 l4">
<div class="card">
<div class="card-image">
<img src="images/kittychong.jpg">
<span class="card-title">Kitty Chong</span>
</div>
<div class="card-content">
<p>As a Makeup Artist (MUA), I hold that ideal imaging of a female is
achieved by exuding her innate beauty and external style in the best light.
Service area within Malaysia.</p>
</div>
<div class="card-action">
<a href="#">Write Review</a>
<a href="#">Book Artist</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="parallax-container valign-wrapper">
<div class="section no-pad-bot">
<div class="container">
<div class="row center">
<h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5>
</div>
</div>
</div>
<div class="parallax"><img src="images/background2.jpg" alt="Unsplashed background img 2"></div>
</div>
<div class="container">
<div class="section">
<div class="row">
<div class="col s12 center">
<h3><i class="mdi-content-send brown-text"></i></h3>
<h4>Contact Us</h4>
<p class="left-align light">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam scelerisque id nunc nec volutpat. Etiam pellentesque tristique arcu, non consequat magna fermentum ac. Cras ut ultricies eros. Maecenas eros justo, ullamcorper a sapien id, viverra ultrices eros. Morbi sem neque, posuere et pretium eget, bibendum sollicitudin lacus. Aliquam eleifend sollicitudin diam, eu mattis nisl maximus sed. Nulla imperdiet semper molestie. Morbi massa odio, condimentum sed ipsum ac, gravida ultrices erat. Nullam eget dignissim mauris, non tristique erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p>
</div>
</div>
</div>
</div>
<div class="parallax-container valign-wrapper">
<div class="section no-pad-bot">
<div class="container">
<div class="row center">
<h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5>
</div>
</div>
</div>
<div class="parallax"><img src="background3.jpg" alt="Unsplashed background img 3"></div>
</div>
<footer class="page-footer teal">
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="white-text">Company Bio</h5>
<p class="grey-text text-lighten-4">We are a team of college students working on this project like it's our full time job. Any amount would help support and continue development on this project and is greatly appreciated.</p>
</div>
<div class="col l3 s12">
<h5 class="white-text">Settings</h5>
<ul>
<li><a class="white-text" href="#!">Link 1</a></li>
<li><a class="white-text" href="#!">Link 2</a></li>
<li><a class="white-text" href="#!">Link 3</a></li>
<li><a class="white-text" href="#!">Link 4</a></li>
</ul>
</div>
<div class="col l3 s12">
<h5 class="white-text">Connect</h5>
<ul>
<li><a class="white-text" href="#!">Link 1</a></li>
<li><a class="white-text" href="#!">Link 2</a></li>
<li><a class="white-text" href="#!">Link 3</a></li>
<li><a class="white-text" href="#!">Link 4</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
Made by <a class="brown-text text-lighten-3" href="http://materializecss.com">Materialize</a>
</div>
</div>
</footer>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="../../dist/js/materialize.js"></script>
<script src="js/init.js"></script>
</body>
</html>
| {
"content_hash": "d9404a821cffd4a6b1e5fa2f80affcd3",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 674,
"avg_line_length": 39.43564356435643,
"alnum_prop": 0.569545568666834,
"repo_name": "blushup/blushup.github.io",
"id": "25779af9379eafc22c2da98a9e63410b64f4477e",
"size": "7966",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "booking.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "191497"
},
{
"name": "HTML",
"bytes": "14885"
},
{
"name": "JavaScript",
"bytes": "257622"
}
],
"symlink_target": ""
} |
html,
body {
height: auto;
}
html {
overflow: auto;
padding: 1in 0.5in;
background: #aeb4ba;
}
body {
width: 8.5in;
margin: 0 auto;
background: ;
font-family: "franklin-gothic-urw", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 500;
font-size: 14px;
line-height: 24px;
background: #ffffff;
color: #2d2e2f;
cursor: auto;
}
div#print_preview_hdr {
position: fixed;
left: 0;
right: 0;
top: 0;
margin: 0;
padding: 1rem;
border: none;
background: #2d2e2f;
font-family: "franklin-gothic-urw", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 500;
font-size: 20px;
color: #ffffff;
}
div#print_preview_hdr div {
background: none !important;
padding: 0 !important;
}
div#print_preview_hdr span.actionlinks {
width: auto;
margin: 0;
font-family: "franklin-gothic-urw", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 500;
color: #2d2e2f;
font-size: 0;
}
div#print_preview_hdr span.actionlinks a {
display: inline-block;
margin-left: 1rem;
padding: .2em .8em;
text-transform: uppercase;
font-weight: 400;
font-size: 11px;
line-height: 18px;
letter-spacing: .1em;
border: 2px solid #e4af0f;
color: #e4af0f;
text-decoration: none;
}
div#print_preview_hdr span.actionlinks a:hover {
text-decoration: none;
}
div#view-container {
margin: 0;
}
div#view-container table.entry-detail-view {
margin: 0;
border-radius: 0;
border: none;
background: none;
}
div#view-container table.entry-detail-view a {
display: inline-block;
color: #003f6b;
border-bottom: 2px solid #003f6b;
text-decoration: none;
}
div#view-container table.entry-detail-view tr.col-md-half {
float: left;
width: 25%;
}
div#view-container table.entry-detail-view th {
padding: 2rem;
background: #e4af0f;
text-shadow: none;
color: #ffffff;
font-size: 1.5em;
}
div#view-container table.entry-detail-view th#details {
width: 100%;
}
div#view-container table.entry-detail-view td.entry-view-section-break {
padding: 3rem 0rem 1rem;
font-size: 2em;
text-transform: uppercase;
background: #aeb4ba;
border-bottom: 3px solid #003f6b;
color: #003f6b;
letter-spacing: .05em;
}
div#view-container table.entry-detail-view td.entry-view-field-name {
padding: 1rem 2rem;
border: none;
line-height: 1.2;
background: rgba(0, 63, 107, 0.1);
}
div#view-container table.entry-detail-view td.entry-view-field-value {
padding: 1rem 2rem 2.5rem;
border: none;
font-size: 1.25em;
line-height: 1.5;
font-weight: 400;
}
div#view-container table.entry-detail-view table.gfield_list,
div#view-container table.entry-detail-view table.entry-products {
border: none !important;
margin: -1rem 0 0;
width: 100%;
}
div#view-container table.entry-detail-view table.gfield_list th,
div#view-container table.entry-detail-view table.entry-products th {
background: none;
font-size: 11px;
color: #e4af0f;
padding: 1rem 0 .25rem;
border: none !important;
border-bottom: 2px solid #e4af0f !important;
text-transform: uppercase;
}
div#view-container table.entry-detail-view table.gfield_list td,
div#view-container table.entry-detail-view table.entry-products td {
padding: .5em 0;
font-size: 1em;
color: #2d2e2f;
border: none !important;
}
div#view-container table.entry-detail-view table.gfield_list td.emptycell,
div#view-container table.entry-detail-view table.entry-products td.emptycell {
background: none;
}
div#view-container table.entry-detail-view table.gfield_list td.grandtotal,
div#view-container table.entry-detail-view table.entry-products td.grandtotal {
padding-right: 1em;
}
div#view-container table.entry-detail-view table.gfield_list td .product_name,
div#view-container table.entry-detail-view table.entry-products td .product_name {
font-size: 1em;
font-weight: 400;
margin: 0;
color: #2d2e2f;
}
/*---- Print Overrides -----*/
@media print {
* {
-webkit-print-color-adjust: exact;
}
html,
body {
background: none;
margin: 0;
padding: 0;
min-height: 0;
box-shadow: none !important;
}
body {
width: 100%;
}
}
@page {
size: 8.5in 11in;
}
| {
"content_hash": "17c9aa6e89d7384c94907617a15129b5",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 85,
"avg_line_length": 24.1046511627907,
"alnum_prop": 0.6985045827303425,
"repo_name": "ndimatteo/yarmouth-theme",
"id": "b2109d349c744b1c4e9e4d3494723fabc4c1209f",
"size": "4146",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/css/print.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "204742"
},
{
"name": "JavaScript",
"bytes": "5327"
},
{
"name": "PHP",
"bytes": "114070"
}
],
"symlink_target": ""
} |
* Invoking params multiple times will append to the existing parameters
## 0.3.0
* Depends on `sprockets < 3` thus source map can still work
* Remove sprockets-es6 from dependency
* Set `displayName` of component as the Ruby class name, which make it displayed better in [react-devtools](https://github.com/facebook/react-devtools)
* Fix React::Element bridging in React Native environment (#fba2daeb)
* React#create_element accept a native component constructor function
## 0.2.1
* Depends on opal `~> 0.6.0`, which accidentally got loosen in previous release
## 0.2.0
* Deprecating `jsx` helper method in component instance
* Deprecating `React::Element.new`, use `React.create_element` instead
* `React::Element` is now toll-free bridge to [ReactElement](http://facebook.github.io/react/docs/glossary.html#react-elements)
* `React::Element#props` now return a `Hash` rather than a `Native`
* `React::Element#children` now handling empty child & single child correctly
| {
"content_hash": "86dd5cf711b790c1a44fa8ba7f6a980e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 152,
"avg_line_length": 51.94736842105263,
"alnum_prop": 0.7537993920972644,
"repo_name": "LeeChSien/react.rb",
"id": "00da48aedf59d7dcc0f99b44db23a4f565ba3ecd",
"size": "996",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "258"
},
{
"name": "Ruby",
"bytes": "58522"
}
],
"symlink_target": ""
} |
/*!
* \file atomic/fences.hpp
*
* This header contains definition of \c atomic_thread_fence and \c atomic_signal_fence functions.
*/
#ifndef BOOST_ATOMIC_FENCES_HPP_INCLUDED_
#define BOOST_ATOMIC_FENCES_HPP_INCLUDED_
#include <boost/memory_order.hpp>
#include <boost/atomic/capabilities.hpp>
#include <boost/atomic/detail/operations.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
/*
* IMPLEMENTATION NOTE: All interface functions MUST be declared with BOOST_FORCEINLINE,
* see comment for convert_memory_order_to_gcc in ops_gcc_atomic.hpp.
*/
namespace boost {
namespace atomics {
#if BOOST_ATOMIC_THREAD_FENCE > 0
BOOST_FORCEINLINE void atomic_thread_fence(memory_order order) BOOST_NOEXCEPT
{
atomics::detail::thread_fence(order);
}
#else
BOOST_FORCEINLINE void atomic_thread_fence(memory_order) BOOST_NOEXCEPT
{
atomics::detail::lock_pool::thread_fence();
}
#endif
#if BOOST_ATOMIC_SIGNAL_FENCE > 0
BOOST_FORCEINLINE void atomic_signal_fence(memory_order order) BOOST_NOEXCEPT
{
atomics::detail::signal_fence(order);
}
#else
BOOST_FORCEINLINE void atomic_signal_fence(memory_order) BOOST_NOEXCEPT
{
atomics::detail::lock_pool::signal_fence();
}
#endif
} // namespace atomics
using atomics::atomic_thread_fence;
using atomics::atomic_signal_fence;
} // namespace boost
#endif // BOOST_ATOMIC_FENCES_HPP_INCLUDED_
| {
"content_hash": "07ca5de216430500d5d7d9d9af37c7d9",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 98,
"avg_line_length": 23.406779661016948,
"alnum_prop": 0.7385952208544533,
"repo_name": "CppMicroServices/CppMicroServices",
"id": "e91f6389bcf6a93119317b19cfa2effb688e7a10",
"size": "1656",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "third_party/boost/include/boost/atomic/fences.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "428"
},
{
"name": "C++",
"bytes": "3299839"
},
{
"name": "CMake",
"bytes": "221280"
},
{
"name": "CSS",
"bytes": "1589"
},
{
"name": "HTML",
"bytes": "9040"
},
{
"name": "JavaScript",
"bytes": "4419"
},
{
"name": "PowerShell",
"bytes": "132"
},
{
"name": "Python",
"bytes": "23871"
},
{
"name": "Scheme",
"bytes": "156"
},
{
"name": "Shell",
"bytes": "615"
}
],
"symlink_target": ""
} |
To schedule the "immediate" execution of `callback` after I/O events
callbacks and before `setTimeout` and `setInterval` . Returns an
`immediateObject` for possible use with `clearImmediate()`. Optionally you
can also pass arguments to the callback.
Callbacks for immediates are queued in the order in which they were created.
The entire callback queue is processed every event loop iteration. If you queue
an immediate from inside an executing callback, that immediate won't fire
until the next event loop iteration. | {
"content_hash": "7580c6d76c183232a8cea70d73829a87",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 79,
"avg_line_length": 57.55555555555556,
"alnum_prop": 0.806949806949807,
"repo_name": "mkaminsky11/iota",
"id": "c4b0afd8db6cd10bd8d4c7e0603dd1e9b94c8375",
"size": "568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/nodejs/nodejs_setImmediate.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "93288"
},
{
"name": "HTML",
"bytes": "6628"
},
{
"name": "JavaScript",
"bytes": "22063"
}
],
"symlink_target": ""
} |
<Musics>
<Default_Trainer_Battle default="1" title="Default_Trainer_Battle.ogg" intro="52"></Default_Trainer_Battle>
<Default_Wild_Battle default="1" title="Default_Wild_Battle.ogg" intro="44"></Default_Wild_Battle>
<Default_LowHP default="1" title="Default_LowHP.ogg" intro="11"></Default_LowHP>
<Sootopolis default="0" title="Sootopolis.ogg" intro="16"></Sootopolis>
</Musics> | {
"content_hash": "026b952e235e8085eb76831d36fd1906",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 111,
"avg_line_length": 67.16666666666667,
"alnum_prop": 0.6972704714640199,
"repo_name": "yongaro/Pokemon",
"id": "34d67f454e1e89640c190cb82ab8143a885f6a3f",
"size": "403",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Pokemon-android/src/main/resources/xml/Musics.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "275557"
},
{
"name": "Makefile",
"bytes": "147"
},
{
"name": "OpenEdge ABL",
"bytes": "17214"
}
],
"symlink_target": ""
} |
const char kMagicBytes[] = "Gact";
const quint32 kPEHeaderOffset = 60;
int ApplyTag::embedTagString()
{
createBufferToWrite();
m_taggedFile.seek(m_taggedFile.size());
m_taggedFile.write(m_tagBuffer);
if (!applyTagToBuffer()) {
m_taggedFile.close();
return WriteError;
}
m_taggedFile.close();
return NoError;
}
int ApplyTag::init(const QString &signedExeFile, const QString &taggedFile, const QByteArray &tag)
{
if (tag.size() != (int) qstrlen(tag.constData()))
return BadTagFormat;
if (tag.size() > 65536)
return TagTooBig;
m_tag = tag;
if (!QFile::exists(signedExeFile))
return SignedExeFileNotExists;
if (QFile::exists(taggedFile) && !QFile::remove(taggedFile))
return TaggedFileUnwritable;
if (!QFile::copy(signedExeFile, taggedFile))
return TaggedFileUnwritable;
m_taggedFile.setFileName(taggedFile);
if (!m_taggedFile.open(QFile::ReadWrite))
return TaggedFileUnwritable;
return NoError;
}
bool ApplyTag::applyTagToBuffer() {
quint32 peHeader = getUint32(kPEHeaderOffset);
quint32 certDirAddressOffset = 152;
// Read certificate directory info.
quint32 certDirOffset = getUint32(peHeader + certDirAddressOffset);
if (certDirOffset == 0)
return false;
quint32 certDirSize = getUint32(peHeader + certDirAddressOffset + 4);
// Increase the size of certificate directory.
int newCertSize = certDirSize + m_tagBuffer.size();
putUint32(newCertSize, peHeader + certDirAddressOffset + 4);
// Increase the certificate struct size.
putUint32(newCertSize, certDirOffset);
return true;
}
quint32 ApplyTag::getUint32(qint64 offset)
{
quint32 out = 0;
m_taggedFile.seek(offset);
m_taggedFile.read((char *) &out, 4);
return out;
}
void ApplyTag::createBufferToWrite()
{
// Build the tag buffer.
// The format of the tag buffer is:
// 000000-000003: 4-byte magic (big-endian)
// 000004-000005: unsigned 16-bit int string length (big-endian)
// 000006-??????: ASCII string
qint16 size = m_tag.size();
int unpaddedSize = size + 6;
// The tag buffer should be padded to multiples of 8, otherwise it will
// break the signature of the executable file.
int paddedSize = (unpaddedSize + 15) & (-8);
m_tagBuffer.clear();
m_tagBuffer.reserve(paddedSize);
m_tagBuffer.append(kMagicBytes);
size = qToBigEndian(size);
m_tagBuffer.append((char *) &size, 2);
m_tagBuffer.append(m_tag);
m_tagBuffer.append(QByteArray().fill('\0', paddedSize - unpaddedSize));
}
void ApplyTag::putUint32(quint32 i, qint64 offset)
{
m_taggedFile.seek(offset);
m_taggedFile.write((char *) &i, 4);
}
| {
"content_hash": "32d3ea4ad77e3712936a0dd1edc42771",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 98,
"avg_line_length": 24.155963302752294,
"alnum_prop": 0.7011014052411698,
"repo_name": "impomezia/ApplyTag",
"id": "0abe794224921535ba26eaa5b05857045e678334",
"size": "3444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ApplyTag.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "7190"
},
{
"name": "IDL",
"bytes": "208"
}
],
"symlink_target": ""
} |
<?php
namespace Asenine\CLI;
interface OptionInterface
{
public function parseArguments(array $arguments);
public function parse($value);
}
class OptionException extends \InvalidArgumentException
{}
abstract class Option implements OptionInterface
{
public $switches;
public $default;
public $value;
public $desc;
public function __construct(array $switches, $default = null, $desc = null)
{
foreach ($switches as $switch) {
if (!is_null($switch) && !is_string($switch)) {
throw new OptionException("$switch is not a valid switch, must be string.");
}
}
$this->switches = $switches;
$this->value = $this->default = $default;
$this->desc = $desc;
}
public function parseArguments(array $arguments)
{
$switch = null;
foreach ($this->switches as $testSwitch) {
if (in_array($testSwitch, $arguments)) {
if ($switch) {
throw new OptionException("Conflicting switches '$switch' and '$testSwitch' specified.");
}
$switch = $testSwitch;
}
}
if (is_null($switch)) {
if (is_null($this->default)) {
throw new OptionException(sprintf("Missing required flag '%s'.", join('/', $this->switches)));
}
}
else {
$i = array_search($switch, $arguments);
$v = array_key_exists($i+1, $arguments) ? $arguments[$i+1] : null;;
// Next value is a flag.
if ($v[0] == '-') {
$v = null;
}
if (!$this->parse($v)) {
throw new OptionException("Flag '$switch' has wrong format.");
}
}
}
} | {
"content_hash": "784b75f6bdad958ca35f53d0976a4db3",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 98,
"avg_line_length": 22.661538461538463,
"alnum_prop": 0.636795655125594,
"repo_name": "pomle/asenine-lib",
"id": "4d0114a680ee200de20ec991261046434936b9e6",
"size": "1473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/CLI/Option.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "140636"
}
],
"symlink_target": ""
} |
<?php
namespace Longman\TelegramBot;
use Longman\TelegramBot\Entities\CallbackQuery;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Entities\ChatJoinRequest;
use Longman\TelegramBot\Entities\ChatMemberUpdated;
use Longman\TelegramBot\Entities\ChosenInlineResult;
use Longman\TelegramBot\Entities\InlineQuery;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\Payments\PreCheckoutQuery;
use Longman\TelegramBot\Entities\Payments\ShippingQuery;
use Longman\TelegramBot\Entities\Poll;
use Longman\TelegramBot\Entities\PollAnswer;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Entities\User;
use Longman\TelegramBot\Exception\TelegramException;
use PDO;
use PDOException;
class DB
{
/**
* MySQL credentials
*
* @var array
*/
protected static $mysql_credentials = [];
/**
* PDO object
*
* @var PDO
*/
protected static $pdo;
/**
* Table prefix
*
* @var string
*/
protected static $table_prefix;
/**
* Telegram class object
*
* @var Telegram
*/
protected static $telegram;
/**
* Initialize
*
* @param array $credentials Database connection details
* @param Telegram $telegram Telegram object to connect with this object
* @param string $table_prefix Table prefix
* @param string $encoding Database character encoding
*
* @return PDO PDO database object
* @throws TelegramException
*/
public static function initialize(
array $credentials,
Telegram $telegram,
$table_prefix = '',
$encoding = 'utf8mb4'
): PDO {
if (empty($credentials)) {
throw new TelegramException('MySQL credentials not provided!');
}
if (isset($credentials['unix_socket'])) {
$dsn = 'mysql:unix_socket=' . $credentials['unix_socket'];
} else {
$dsn = 'mysql:host=' . $credentials['host'];
}
$dsn .= ';dbname=' . $credentials['database'];
if (!empty($credentials['port'])) {
$dsn .= ';port=' . $credentials['port'];
}
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $encoding];
try {
$pdo = new PDO($dsn, $credentials['user'], $credentials['password'], $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
self::$pdo = $pdo;
self::$telegram = $telegram;
self::$mysql_credentials = $credentials;
self::$table_prefix = $table_prefix;
self::defineTables();
return self::$pdo;
}
/**
* External Initialize
*
* Let you use the class with an external already existing Pdo Mysql connection.
*
* @param PDO $external_pdo_connection PDO database object
* @param Telegram $telegram Telegram object to connect with this object
* @param string $table_prefix Table prefix
*
* @return PDO PDO database object
* @throws TelegramException
*/
public static function externalInitialize(
PDO $external_pdo_connection,
Telegram $telegram,
string $table_prefix = ''
): PDO {
if ($external_pdo_connection === null) {
throw new TelegramException('MySQL external connection not provided!');
}
self::$pdo = $external_pdo_connection;
self::$telegram = $telegram;
self::$mysql_credentials = [];
self::$table_prefix = $table_prefix;
self::defineTables();
return self::$pdo;
}
/**
* Define all the tables with the proper prefix
*/
protected static function defineTables(): void
{
$tables = [
'callback_query',
'chat',
'chat_join_request',
'chat_member_updated',
'chosen_inline_result',
'edited_message',
'inline_query',
'message',
'poll',
'poll_answer',
'pre_checkout_query',
'request_limiter',
'shipping_query',
'telegram_update',
'user',
'user_chat',
];
foreach ($tables as $table) {
$table_name = 'TB_' . strtoupper($table);
if (!defined($table_name)) {
define($table_name, self::$table_prefix . $table);
}
}
}
/**
* Check if database connection has been created
*
* @return bool
*/
public static function isDbConnected(): bool
{
return self::$pdo !== null;
}
/**
* Get the PDO object of the connected database
*
* @return PDO|null
*/
public static function getPdo(): ?PDO
{
return self::$pdo;
}
/**
* Fetch update(s) from DB
*
* @param int $limit Limit the number of updates to fetch
* @param string $id Check for unique update id
*
* @return array|bool Fetched data or false if not connected
* @throws TelegramException
*/
public static function selectTelegramUpdate(int $limit = 0, string $id = '')
{
if (!self::isDbConnected()) {
return false;
}
try {
$sql = '
SELECT `id`
FROM `' . TB_TELEGRAM_UPDATE . '`
';
if ($id !== '') {
$sql .= ' WHERE `id` = :id';
} else {
$sql .= ' ORDER BY `id` DESC';
}
if ($limit > 0) {
$sql .= ' LIMIT :limit';
}
$sth = self::$pdo->prepare($sql);
if ($limit > 0) {
$sth->bindValue(':limit', $limit, PDO::PARAM_INT);
}
if ($id !== '') {
$sth->bindValue(':id', $id);
}
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Fetch message(s) from DB
*
* @param int $limit Limit the number of messages to fetch
*
* @return array|bool Fetched data or false if not connected
* @throws TelegramException
*/
public static function selectMessages(int $limit = 0)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sql = '
SELECT *
FROM `' . TB_MESSAGE . '`
ORDER BY `id` DESC
';
if ($limit > 0) {
$sql .= ' LIMIT :limit';
}
$sth = self::$pdo->prepare($sql);
if ($limit > 0) {
$sth->bindValue(':limit', $limit, PDO::PARAM_INT);
}
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Convert from unix timestamp to timestamp
*
* @param ?int $unixtime Unix timestamp (if empty, current timestamp is used)
*
* @return string
*/
protected static function getTimestamp(?int $unixtime = null): string
{
return date('Y-m-d H:i:s', $unixtime ?? time());
}
/**
* Convert array of Entity items to a JSON array
*
* @todo Find a better way, as json_* functions are very heavy
*
* @param array $entities
* @param mixed $default
*
* @return mixed
*/
public static function entitiesArrayToJson(array $entities, $default = null)
{
if (empty($entities)) {
return $default;
}
// Convert each Entity item into an object based on its JSON reflection
$json_entities = array_map(function ($entity) {
return json_decode($entity, true);
}, $entities);
return json_encode($json_entities);
}
/**
* Insert entry to telegram_update table
*
* @param int $update_id
* @param int|null $chat_id
* @param int|null $message_id
* @param int|null $edited_message_id
* @param int|null $channel_post_id
* @param int|null $edited_channel_post_id
* @param string|null $inline_query_id
* @param string|null $chosen_inline_result_id
* @param string|null $callback_query_id
* @param string|null $shipping_query_id
* @param string|null $pre_checkout_query_id
* @param string|null $poll_id
* @param string|null $poll_answer_poll_id
* @param string|null $my_chat_member_updated_id
* @param string|null $chat_member_updated_id
*
* @return bool If the insert was successful
* @throws TelegramException
*/
protected static function insertTelegramUpdate(
int $update_id,
?int $chat_id = null,
?int $message_id = null,
?int $edited_message_id = null,
?int $channel_post_id = null,
?int $edited_channel_post_id = null,
?string $inline_query_id = null,
?string $chosen_inline_result_id = null,
?string $callback_query_id = null,
?string $shipping_query_id = null,
?string $pre_checkout_query_id = null,
?string $poll_id = null,
?string $poll_answer_poll_id = null,
?string $my_chat_member_updated_id = null,
?string $chat_member_updated_id = null,
?string $chat_join_request_id = null
): ?bool {
if ($message_id === null && $edited_message_id === null && $channel_post_id === null && $edited_channel_post_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $shipping_query_id === null && $pre_checkout_query_id === null && $poll_id === null && $poll_answer_poll_id === null && $my_chat_member_updated_id === null && $chat_member_updated_id === null && $chat_join_request_id === null) {
throw new TelegramException('message_id, edited_message_id, channel_post_id, edited_channel_post_id, inline_query_id, chosen_inline_result_id, callback_query_id, shipping_query_id, pre_checkout_query_id, poll_id, poll_answer_poll_id, my_chat_member_updated_id, chat_member_updated_id are all null');
}
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '`
(
`id`, `chat_id`, `message_id`, `edited_message_id`,
`channel_post_id`, `edited_channel_post_id`, `inline_query_id`, `chosen_inline_result_id`,
`callback_query_id`, `shipping_query_id`, `pre_checkout_query_id`,
`poll_id`, `poll_answer_poll_id`, `my_chat_member_updated_id`, `chat_member_updated_id`,
`chat_join_request_id`
) VALUES (
:id, :chat_id, :message_id, :edited_message_id,
:channel_post_id, :edited_channel_post_id, :inline_query_id, :chosen_inline_result_id,
:callback_query_id, :shipping_query_id, :pre_checkout_query_id,
:poll_id, :poll_answer_poll_id, :my_chat_member_updated_id, :chat_member_updated_id,
:chat_join_request_id
)
');
$sth->bindValue(':id', $update_id);
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':message_id', $message_id);
$sth->bindValue(':edited_message_id', $edited_message_id);
$sth->bindValue(':channel_post_id', $channel_post_id);
$sth->bindValue(':edited_channel_post_id', $edited_channel_post_id);
$sth->bindValue(':inline_query_id', $inline_query_id);
$sth->bindValue(':chosen_inline_result_id', $chosen_inline_result_id);
$sth->bindValue(':callback_query_id', $callback_query_id);
$sth->bindValue(':shipping_query_id', $shipping_query_id);
$sth->bindValue(':pre_checkout_query_id', $pre_checkout_query_id);
$sth->bindValue(':poll_id', $poll_id);
$sth->bindValue(':poll_answer_poll_id', $poll_answer_poll_id);
$sth->bindValue(':my_chat_member_updated_id', $my_chat_member_updated_id);
$sth->bindValue(':chat_member_updated_id', $chat_member_updated_id);
$sth->bindValue(':chat_join_request_id', $chat_join_request_id);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert users and save their connection to chats
*
* @param User $user
* @param string|null $date
* @param Chat|null $chat
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertUser(User $user, ?string $date = null, ?Chat $chat = null): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_USER . '`
(`id`, `is_bot`, `username`, `first_name`, `last_name`, `language_code`, `created_at`, `updated_at`)
VALUES
(:id, :is_bot, :username, :first_name, :last_name, :language_code, :created_at, :updated_at)
ON DUPLICATE KEY UPDATE
`is_bot` = VALUES(`is_bot`),
`username` = VALUES(`username`),
`first_name` = VALUES(`first_name`),
`last_name` = VALUES(`last_name`),
`language_code` = VALUES(`language_code`),
`updated_at` = VALUES(`updated_at`)
');
$sth->bindValue(':id', $user->getId());
$sth->bindValue(':is_bot', $user->getIsBot(), PDO::PARAM_INT);
$sth->bindValue(':username', $user->getUsername());
$sth->bindValue(':first_name', $user->getFirstName());
$sth->bindValue(':last_name', $user->getLastName());
$sth->bindValue(':language_code', $user->getLanguageCode());
$date = $date ?: self::getTimestamp();
$sth->bindValue(':created_at', $date);
$sth->bindValue(':updated_at', $date);
$status = $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
// Also insert the relationship to the chat into the user_chat table
if ($chat) {
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_USER_CHAT . '`
(`user_id`, `chat_id`)
VALUES
(:user_id, :chat_id)
');
$sth->bindValue(':user_id', $user->getId());
$sth->bindValue(':chat_id', $chat->getId());
$status = $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
return $status;
}
/**
* Insert chat
*
* @param Chat $chat
* @param string|null $date
* @param int|null $migrate_to_chat_id
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChat(Chat $chat, ?string $date = null, ?int $migrate_to_chat_id = null): ?bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_CHAT . '`
(`id`, `type`, `title`, `username`, `first_name`, `last_name`, `all_members_are_administrators`, `created_at` ,`updated_at`, `old_id`)
VALUES
(:id, :type, :title, :username, :first_name, :last_name, :all_members_are_administrators, :created_at, :updated_at, :old_id)
ON DUPLICATE KEY UPDATE
`type` = VALUES(`type`),
`title` = VALUES(`title`),
`username` = VALUES(`username`),
`first_name` = VALUES(`first_name`),
`last_name` = VALUES(`last_name`),
`all_members_are_administrators` = VALUES(`all_members_are_administrators`),
`updated_at` = VALUES(`updated_at`)
');
$chat_id = $chat->getId();
$chat_type = $chat->getType();
if ($migrate_to_chat_id !== null) {
$chat_type = 'supergroup';
$sth->bindValue(':id', $migrate_to_chat_id);
$sth->bindValue(':old_id', $chat_id);
} else {
$sth->bindValue(':id', $chat_id);
$sth->bindValue(':old_id', $migrate_to_chat_id);
}
$sth->bindValue(':type', $chat_type);
$sth->bindValue(':title', $chat->getTitle());
$sth->bindValue(':username', $chat->getUsername());
$sth->bindValue(':first_name', $chat->getFirstName());
$sth->bindValue(':last_name', $chat->getLastName());
$sth->bindValue(':all_members_are_administrators', $chat->getAllMembersAreAdministrators(), PDO::PARAM_INT);
$date = $date ?: self::getTimestamp();
$sth->bindValue(':created_at', $date);
$sth->bindValue(':updated_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert request into database
*
* @todo self::$pdo->lastInsertId() - unsafe usage if expected previous insert fails?
*
* @param Update $update
*
* @return bool
* @throws TelegramException
*/
public static function insertRequest(Update $update): bool
{
if (!self::isDbConnected()) {
return false;
}
$chat_id = null;
$message_id = null;
$edited_message_id = null;
$channel_post_id = null;
$edited_channel_post_id = null;
$inline_query_id = null;
$chosen_inline_result_id = null;
$callback_query_id = null;
$shipping_query_id = null;
$pre_checkout_query_id = null;
$poll_id = null;
$poll_answer_poll_id = null;
$my_chat_member_updated_id = null;
$chat_member_updated_id = null;
$chat_join_request_id = null;
if (($message = $update->getMessage()) && self::insertMessageRequest($message)) {
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
} elseif (($edited_message = $update->getEditedMessage()) && self::insertEditedMessageRequest($edited_message)) {
$chat_id = $edited_message->getChat()->getId();
$edited_message_id = (int) self::$pdo->lastInsertId();
} elseif (($channel_post = $update->getChannelPost()) && self::insertMessageRequest($channel_post)) {
$chat_id = $channel_post->getChat()->getId();
$channel_post_id = $channel_post->getMessageId();
} elseif (($edited_channel_post = $update->getEditedChannelPost()) && self::insertEditedMessageRequest($edited_channel_post)) {
$chat_id = $edited_channel_post->getChat()->getId();
$edited_channel_post_id = (int) self::$pdo->lastInsertId();
} elseif (($inline_query = $update->getInlineQuery()) && self::insertInlineQueryRequest($inline_query)) {
$inline_query_id = $inline_query->getId();
} elseif (($chosen_inline_result = $update->getChosenInlineResult()) && self::insertChosenInlineResultRequest($chosen_inline_result)) {
$chosen_inline_result_id = self::$pdo->lastInsertId();
} elseif (($callback_query = $update->getCallbackQuery()) && self::insertCallbackQueryRequest($callback_query)) {
$callback_query_id = $callback_query->getId();
} elseif (($shipping_query = $update->getShippingQuery()) && self::insertShippingQueryRequest($shipping_query)) {
$shipping_query_id = $shipping_query->getId();
} elseif (($pre_checkout_query = $update->getPreCheckoutQuery()) && self::insertPreCheckoutQueryRequest($pre_checkout_query)) {
$pre_checkout_query_id = $pre_checkout_query->getId();
} elseif (($poll = $update->getPoll()) && self::insertPollRequest($poll)) {
$poll_id = $poll->getId();
} elseif (($poll_answer = $update->getPollAnswer()) && self::insertPollAnswerRequest($poll_answer)) {
$poll_answer_poll_id = $poll_answer->getPollId();
} elseif (($my_chat_member = $update->getMyChatMember()) && self::insertChatMemberUpdatedRequest($my_chat_member)) {
$my_chat_member_updated_id = self::$pdo->lastInsertId();
} elseif (($chat_member = $update->getChatMember()) && self::insertChatMemberUpdatedRequest($chat_member)) {
$chat_member_updated_id = self::$pdo->lastInsertId();
} elseif (($chat_join_request = $update->getChatJoinRequest()) && self::insertChatJoinRequestRequest($chat_join_request)) {
$chat_join_request_id = self::$pdo->lastInsertId();
} else {
return false;
}
return self::insertTelegramUpdate(
$update->getUpdateId(),
$chat_id,
$message_id,
$edited_message_id,
$channel_post_id,
$edited_channel_post_id,
$inline_query_id,
$chosen_inline_result_id,
$callback_query_id,
$shipping_query_id,
$pre_checkout_query_id,
$poll_id,
$poll_answer_poll_id,
$my_chat_member_updated_id,
$chat_member_updated_id,
$chat_join_request_id
);
}
/**
* Insert inline query request into database
*
* @param InlineQuery $inline_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertInlineQueryRequest(InlineQuery $inline_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_INLINE_QUERY . '`
(`id`, `user_id`, `location`, `query`, `offset`, `chat_type`, `created_at`)
VALUES
(:id, :user_id, :location, :query, :offset, :chat_type, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $inline_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':id', $inline_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':location', $inline_query->getLocation());
$sth->bindValue(':query', $inline_query->getQuery());
$sth->bindValue(':offset', $inline_query->getOffset());
$sth->bindValue(':chat_type', $inline_query->getChatType());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert chosen inline result request into database
*
* @param ChosenInlineResult $chosen_inline_result
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChosenInlineResultRequest(ChosenInlineResult $chosen_inline_result): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '`
(`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at`)
VALUES
(:result_id, :user_id, :location, :inline_message_id, :query, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $chosen_inline_result->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':result_id', $chosen_inline_result->getResultId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':location', $chosen_inline_result->getLocation());
$sth->bindValue(':inline_message_id', $chosen_inline_result->getInlineMessageId());
$sth->bindValue(':query', $chosen_inline_result->getQuery());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert callback query request into database
*
* @param CallbackQuery $callback_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertCallbackQueryRequest(CallbackQuery $callback_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '`
(`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `chat_instance`, `data`, `game_short_name`, `created_at`)
VALUES
(:id, :user_id, :chat_id, :message_id, :inline_message_id, :chat_instance, :data, :game_short_name, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $callback_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$chat_id = null;
$message_id = null;
if ($message = $callback_query->getMessage()) {
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$is_message = self::$pdo->query('
SELECT *
FROM `' . TB_MESSAGE . '`
WHERE `id` = ' . $message_id . '
AND `chat_id` = ' . $chat_id . '
LIMIT 1
')->rowCount();
if ($is_message) {
self::insertEditedMessageRequest($message);
} else {
self::insertMessageRequest($message);
}
}
$sth->bindValue(':id', $callback_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':message_id', $message_id);
$sth->bindValue(':inline_message_id', $callback_query->getInlineMessageId());
$sth->bindValue(':chat_instance', $callback_query->getChatInstance());
$sth->bindValue(':data', $callback_query->getData());
$sth->bindValue(':game_short_name', $callback_query->getGameShortName());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert shipping query request into database
*
* @param ShippingQuery $shipping_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertShippingQueryRequest(ShippingQuery $shipping_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_SHIPPING_QUERY . '`
(`id`, `user_id`, `invoice_payload`, `shipping_address`, `created_at`)
VALUES
(:id, :user_id, :invoice_payload, :shipping_address, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $shipping_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':id', $shipping_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':invoice_payload', $shipping_query->getInvoicePayload());
$sth->bindValue(':shipping_address', $shipping_query->getShippingAddress());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert pre checkout query request into database
*
* @param PreCheckoutQuery $pre_checkout_query
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPreCheckoutQueryRequest(PreCheckoutQuery $pre_checkout_query): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_PRE_CHECKOUT_QUERY . '`
(`id`, `user_id`, `currency`, `total_amount`, `invoice_payload`, `shipping_option_id`, `order_info`, `created_at`)
VALUES
(:id, :user_id, :currency, :total_amount, :invoice_payload, :shipping_option_id, :order_info, :created_at)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $pre_checkout_query->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':id', $pre_checkout_query->getId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':currency', $pre_checkout_query->getCurrency());
$sth->bindValue(':total_amount', $pre_checkout_query->getTotalAmount());
$sth->bindValue(':invoice_payload', $pre_checkout_query->getInvoicePayload());
$sth->bindValue(':shipping_option_id', $pre_checkout_query->getShippingOptionId());
$sth->bindValue(':order_info', $pre_checkout_query->getOrderInfo());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert poll request into database
*
* @param Poll $poll
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPollRequest(Poll $poll): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_POLL . '`
(`id`, `question`, `options`, `total_voter_count`, `is_closed`, `is_anonymous`, `type`, `allows_multiple_answers`, `correct_option_id`, `explanation`, `explanation_entities`, `open_period`, `close_date`, `created_at`)
VALUES
(:id, :question, :options, :total_voter_count, :is_closed, :is_anonymous, :type, :allows_multiple_answers, :correct_option_id, :explanation, :explanation_entities, :open_period, :close_date, :created_at)
ON DUPLICATE KEY UPDATE
`options` = VALUES(`options`),
`total_voter_count` = VALUES(`total_voter_count`),
`is_closed` = VALUES(`is_closed`),
`is_anonymous` = VALUES(`is_anonymous`),
`type` = VALUES(`type`),
`allows_multiple_answers` = VALUES(`allows_multiple_answers`),
`correct_option_id` = VALUES(`correct_option_id`),
`explanation` = VALUES(`explanation`),
`explanation_entities` = VALUES(`explanation_entities`),
`open_period` = VALUES(`open_period`),
`close_date` = VALUES(`close_date`)
');
$sth->bindValue(':id', $poll->getId());
$sth->bindValue(':question', $poll->getQuestion());
$sth->bindValue(':options', self::entitiesArrayToJson($poll->getOptions() ?: []));
$sth->bindValue(':total_voter_count', $poll->getTotalVoterCount());
$sth->bindValue(':is_closed', $poll->getIsClosed(), PDO::PARAM_INT);
$sth->bindValue(':is_anonymous', $poll->getIsAnonymous(), PDO::PARAM_INT);
$sth->bindValue(':type', $poll->getType());
$sth->bindValue(':allows_multiple_answers', $poll->getAllowsMultipleAnswers(), PDO::PARAM_INT);
$sth->bindValue(':correct_option_id', $poll->getCorrectOptionId());
$sth->bindValue(':explanation', $poll->getExplanation());
$sth->bindValue(':explanation_entities', self::entitiesArrayToJson($poll->getExplanationEntities() ?: []));
$sth->bindValue(':open_period', $poll->getOpenPeriod());
$sth->bindValue(':close_date', self::getTimestamp($poll->getCloseDate()));
$sth->bindValue(':created_at', self::getTimestamp());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert poll answer request into database
*
* @param PollAnswer $poll_answer
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertPollAnswerRequest(PollAnswer $poll_answer): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_POLL_ANSWER . '`
(`poll_id`, `user_id`, `option_ids`, `created_at`)
VALUES
(:poll_id, :user_id, :option_ids, :created_at)
ON DUPLICATE KEY UPDATE
`option_ids` = VALUES(`option_ids`)
');
$date = self::getTimestamp();
$user_id = null;
if ($user = $poll_answer->getUser()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':poll_id', $poll_answer->getPollId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':option_ids', json_encode($poll_answer->getOptionIds()));
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert chat member updated request into database
*
* @param ChatMemberUpdated $chat_member_updated
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChatMemberUpdatedRequest(ChatMemberUpdated $chat_member_updated): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_CHAT_MEMBER_UPDATED . '`
(`chat_id`, `user_id`, `date`, `old_chat_member`, `new_chat_member`, `invite_link`, `created_at`)
VALUES
(:chat_id, :user_id, :date, :old_chat_member, :new_chat_member, :invite_link, :created_at)
');
$date = self::getTimestamp();
$chat_id = null;
$user_id = null;
if ($chat = $chat_member_updated->getChat()) {
$chat_id = $chat->getId();
self::insertChat($chat, $date);
}
if ($user = $chat_member_updated->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':date', self::getTimestamp($chat_member_updated->getDate()));
$sth->bindValue(':old_chat_member', $chat_member_updated->getOldChatMember());
$sth->bindValue(':new_chat_member', $chat_member_updated->getNewChatMember());
$sth->bindValue(':invite_link', $chat_member_updated->getInviteLink());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert chat join request into database
*
* @param ChatJoinRequest $chat_join_request
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertChatJoinRequestRequest(ChatJoinRequest $chat_join_request): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('
INSERT INTO `' . TB_CHAT_JOIN_REQUEST . '`
(`chat_id`, `user_id`, `date`, `bio`, `invite_link`, `created_at`)
VALUES
(:chat_id, :user_id, :date, :bio, :invite_link, :created_at)
');
$date = self::getTimestamp();
$chat_id = null;
$user_id = null;
if ($chat = $chat_join_request->getChat()) {
$chat_id = $chat->getId();
self::insertChat($chat, $date);
}
if ($user = $chat_join_request->getFrom()) {
$user_id = $user->getId();
self::insertUser($user, $date);
}
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':date', self::getTimestamp($chat_join_request->getDate()));
$sth->bindValue(':bio', $chat_join_request->getBio());
$sth->bindValue(':invite_link', $chat_join_request->getInviteLink());
$sth->bindValue(':created_at', $date);
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert Message request in db
*
* @param Message $message
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertMessageRequest(Message $message): bool
{
if (!self::isDbConnected()) {
return false;
}
$date = self::getTimestamp($message->getDate());
// Insert chat, update chat id in case it migrated
$chat = $message->getChat();
self::insertChat($chat, $date, $message->getMigrateToChatId());
$sender_chat_id = null;
if ($sender_chat = $message->getSenderChat()) {
self::insertChat($sender_chat);
$sender_chat_id = $sender_chat->getId();
}
// Insert user and the relation with the chat
if ($user = $message->getFrom()) {
self::insertUser($user, $date, $chat);
}
// Insert the forwarded message user in users table
$forward_date = $message->getForwardDate() ? self::getTimestamp($message->getForwardDate()) : null;
if ($forward_from = $message->getForwardFrom()) {
self::insertUser($forward_from);
$forward_from = $forward_from->getId();
}
if ($forward_from_chat = $message->getForwardFromChat()) {
self::insertChat($forward_from_chat);
$forward_from_chat = $forward_from_chat->getId();
}
$via_bot_id = null;
if ($via_bot = $message->getViaBot()) {
self::insertUser($via_bot);
$via_bot_id = $via_bot->getId();
}
// New and left chat member
$new_chat_members_ids = null;
$left_chat_member_id = null;
$new_chat_members = $message->getNewChatMembers();
$left_chat_member = $message->getLeftChatMember();
if (!empty($new_chat_members)) {
foreach ($new_chat_members as $new_chat_member) {
if ($new_chat_member instanceof User) {
// Insert the new chat user
self::insertUser($new_chat_member, $date, $chat);
$new_chat_members_ids[] = $new_chat_member->getId();
}
}
$new_chat_members_ids = implode(',', $new_chat_members_ids);
} elseif ($left_chat_member) {
// Insert the left chat user
self::insertUser($left_chat_member, $date, $chat);
$left_chat_member_id = $left_chat_member->getId();
}
try {
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_MESSAGE . '`
(
`id`, `user_id`, `chat_id`, `sender_chat_id`, `date`, `forward_from`, `forward_from_chat`, `forward_from_message_id`,
`forward_signature`, `forward_sender_name`, `forward_date`,
`reply_to_chat`, `reply_to_message`, `via_bot`, `edit_date`, `media_group_id`, `author_signature`, `text`, `entities`, `caption_entities`,
`audio`, `document`, `animation`, `game`, `photo`, `sticker`, `video`, `voice`, `video_note`, `caption`, `contact`,
`location`, `venue`, `poll`, `dice`, `new_chat_members`, `left_chat_member`,
`new_chat_title`, `new_chat_photo`, `delete_chat_photo`, `group_chat_created`,
`supergroup_chat_created`, `channel_chat_created`, `message_auto_delete_timer_changed`, `migrate_to_chat_id`, `migrate_from_chat_id`,
`pinned_message`, `invoice`, `successful_payment`, `connected_website`, `passport_data`, `proximity_alert_triggered`,
`voice_chat_scheduled`, `voice_chat_started`, `voice_chat_ended`, `voice_chat_participants_invited`, `reply_markup`
) VALUES (
:message_id, :user_id, :chat_id, :sender_chat_id, :date, :forward_from, :forward_from_chat, :forward_from_message_id,
:forward_signature, :forward_sender_name, :forward_date,
:reply_to_chat, :reply_to_message, :via_bot, :edit_date, :media_group_id, :author_signature, :text, :entities, :caption_entities,
:audio, :document, :animation, :game, :photo, :sticker, :video, :voice, :video_note, :caption, :contact,
:location, :venue, :poll, :dice, :new_chat_members, :left_chat_member,
:new_chat_title, :new_chat_photo, :delete_chat_photo, :group_chat_created,
:supergroup_chat_created, :channel_chat_created, :message_auto_delete_timer_changed, :migrate_to_chat_id, :migrate_from_chat_id,
:pinned_message, :invoice, :successful_payment, :connected_website, :passport_data, :proximity_alert_triggered,
:voice_chat_scheduled, :voice_chat_started, :voice_chat_ended, :voice_chat_participants_invited, :reply_markup
)
');
$user_id = $user ? $user->getId() : null;
$chat_id = $chat->getId();
$reply_to_message_id = null;
if ($reply_to_message = $message->getReplyToMessage()) {
$reply_to_message_id = $reply_to_message->getMessageId();
// please notice that, as explained in the documentation, reply_to_message don't contain other
// reply_to_message field so recursion deep is 1
self::insertMessageRequest($reply_to_message);
}
$sth->bindValue(':message_id', $message->getMessageId());
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':sender_chat_id', $sender_chat_id);
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':date', $date);
$sth->bindValue(':forward_from', $forward_from);
$sth->bindValue(':forward_from_chat', $forward_from_chat);
$sth->bindValue(':forward_from_message_id', $message->getForwardFromMessageId());
$sth->bindValue(':forward_signature', $message->getForwardSignature());
$sth->bindValue(':forward_sender_name', $message->getForwardSenderName());
$sth->bindValue(':forward_date', $forward_date);
$reply_to_chat_id = null;
if ($reply_to_message_id !== null) {
$reply_to_chat_id = $chat_id;
}
$sth->bindValue(':reply_to_chat', $reply_to_chat_id);
$sth->bindValue(':reply_to_message', $reply_to_message_id);
$sth->bindValue(':via_bot', $via_bot_id);
$sth->bindValue(':edit_date', self::getTimestamp($message->getEditDate()));
$sth->bindValue(':media_group_id', $message->getMediaGroupId());
$sth->bindValue(':author_signature', $message->getAuthorSignature());
$sth->bindValue(':text', $message->getText());
$sth->bindValue(':entities', self::entitiesArrayToJson($message->getEntities() ?: []));
$sth->bindValue(':caption_entities', self::entitiesArrayToJson($message->getCaptionEntities() ?: []));
$sth->bindValue(':audio', $message->getAudio());
$sth->bindValue(':document', $message->getDocument());
$sth->bindValue(':animation', $message->getAnimation());
$sth->bindValue(':game', $message->getGame());
$sth->bindValue(':photo', self::entitiesArrayToJson($message->getPhoto() ?: []));
$sth->bindValue(':sticker', $message->getSticker());
$sth->bindValue(':video', $message->getVideo());
$sth->bindValue(':voice', $message->getVoice());
$sth->bindValue(':video_note', $message->getVideoNote());
$sth->bindValue(':caption', $message->getCaption());
$sth->bindValue(':contact', $message->getContact());
$sth->bindValue(':location', $message->getLocation());
$sth->bindValue(':venue', $message->getVenue());
$sth->bindValue(':poll', $message->getPoll());
$sth->bindValue(':dice', $message->getDice());
$sth->bindValue(':new_chat_members', $new_chat_members_ids);
$sth->bindValue(':left_chat_member', $left_chat_member_id);
$sth->bindValue(':new_chat_title', $message->getNewChatTitle());
$sth->bindValue(':new_chat_photo', self::entitiesArrayToJson($message->getNewChatPhoto() ?: []));
$sth->bindValue(':delete_chat_photo', $message->getDeleteChatPhoto());
$sth->bindValue(':group_chat_created', $message->getGroupChatCreated());
$sth->bindValue(':supergroup_chat_created', $message->getSupergroupChatCreated());
$sth->bindValue(':channel_chat_created', $message->getChannelChatCreated());
$sth->bindValue(':message_auto_delete_timer_changed', $message->getMessageAutoDeleteTimerChanged());
$sth->bindValue(':migrate_to_chat_id', $message->getMigrateToChatId());
$sth->bindValue(':migrate_from_chat_id', $message->getMigrateFromChatId());
$sth->bindValue(':pinned_message', $message->getPinnedMessage());
$sth->bindValue(':invoice', $message->getInvoice());
$sth->bindValue(':successful_payment', $message->getSuccessfulPayment());
$sth->bindValue(':connected_website', $message->getConnectedWebsite());
$sth->bindValue(':passport_data', $message->getPassportData());
$sth->bindValue(':proximity_alert_triggered', $message->getProximityAlertTriggered());
$sth->bindValue(':voice_chat_scheduled', $message->getVoiceChatScheduled());
$sth->bindValue(':voice_chat_started', $message->getVoiceChatStarted());
$sth->bindValue(':voice_chat_ended', $message->getVoiceChatEnded());
$sth->bindValue(':voice_chat_participants_invited', $message->getVoiceChatParticipantsInvited());
$sth->bindValue(':reply_markup', $message->getReplyMarkup());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert Edited Message request in db
*
* @param Message $edited_message
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertEditedMessageRequest(Message $edited_message): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$edit_date = self::getTimestamp($edited_message->getEditDate());
// Insert chat
$chat = $edited_message->getChat();
self::insertChat($chat, $edit_date);
// Insert user and the relation with the chat
if ($user = $edited_message->getFrom()) {
self::insertUser($user, $edit_date, $chat);
}
$sth = self::$pdo->prepare('
INSERT IGNORE INTO `' . TB_EDITED_MESSAGE . '`
(`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption`)
VALUES
(:chat_id, :message_id, :user_id, :edit_date, :text, :entities, :caption)
');
$user_id = $user ? $user->getId() : null;
$sth->bindValue(':chat_id', $chat->getId());
$sth->bindValue(':message_id', $edited_message->getMessageId());
$sth->bindValue(':user_id', $user_id);
$sth->bindValue(':edit_date', $edit_date);
$sth->bindValue(':text', $edited_message->getText());
$sth->bindValue(':entities', self::entitiesArrayToJson($edited_message->getEntities() ?: []));
$sth->bindValue(':caption', $edited_message->getCaption());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Select Groups, Supergroups, Channels and/or single user Chats (also by ID or text)
*
* @param $select_chats_params
*
* @return array|bool
* @throws TelegramException
*/
public static function selectChats($select_chats_params)
{
if (!self::isDbConnected()) {
return false;
}
// Set defaults for omitted values.
$select = array_merge([
'groups' => true,
'supergroups' => true,
'channels' => true,
'users' => true,
'date_from' => null,
'date_to' => null,
'chat_id' => null,
'text' => null,
'language' => null,
], $select_chats_params);
if (!$select['groups'] && !$select['users'] && !$select['supergroups'] && !$select['channels']) {
return false;
}
try {
$query = '
SELECT * ,
' . TB_CHAT . '.`id` AS `chat_id`,
' . TB_CHAT . '.`username` AS `chat_username`,
' . TB_CHAT . '.`created_at` AS `chat_created_at`,
' . TB_CHAT . '.`updated_at` AS `chat_updated_at`
';
if ($select['users']) {
$query .= '
, ' . TB_USER . '.`id` AS `user_id`
FROM `' . TB_CHAT . '`
LEFT JOIN `' . TB_USER . '`
ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id`
';
} else {
$query .= 'FROM `' . TB_CHAT . '`';
}
// Building parts of query
$where = [];
$tokens = [];
if (!$select['groups'] || !$select['users'] || !$select['supergroups'] || !$select['channels']) {
$chat_or_user = [];
$select['groups'] && $chat_or_user[] = TB_CHAT . '.`type` = "group"';
$select['supergroups'] && $chat_or_user[] = TB_CHAT . '.`type` = "supergroup"';
$select['channels'] && $chat_or_user[] = TB_CHAT . '.`type` = "channel"';
$select['users'] && $chat_or_user[] = TB_CHAT . '.`type` = "private"';
$where[] = '(' . implode(' OR ', $chat_or_user) . ')';
}
if (null !== $select['date_from']) {
$where[] = TB_CHAT . '.`updated_at` >= :date_from';
$tokens[':date_from'] = $select['date_from'];
}
if (null !== $select['date_to']) {
$where[] = TB_CHAT . '.`updated_at` <= :date_to';
$tokens[':date_to'] = $select['date_to'];
}
if (null !== $select['chat_id']) {
$where[] = TB_CHAT . '.`id` = :chat_id';
$tokens[':chat_id'] = $select['chat_id'];
}
if ($select['users'] && null !== $select['language']) {
$where[] = TB_USER . '.`language_code` = :language';
$tokens[':language'] = $select['language'];
}
if (null !== $select['text']) {
$text_like = '%' . strtolower($select['text']) . '%';
if ($select['users']) {
$where[] = '(
LOWER(' . TB_CHAT . '.`title`) LIKE :text1
OR LOWER(' . TB_USER . '.`first_name`) LIKE :text2
OR LOWER(' . TB_USER . '.`last_name`) LIKE :text3
OR LOWER(' . TB_USER . '.`username`) LIKE :text4
)';
$tokens[':text1'] = $text_like;
$tokens[':text2'] = $text_like;
$tokens[':text3'] = $text_like;
$tokens[':text4'] = $text_like;
} else {
$where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text';
$tokens[':text'] = $text_like;
}
}
if (!empty($where)) {
$query .= ' WHERE ' . implode(' AND ', $where);
}
$query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC';
$sth = self::$pdo->prepare($query);
$sth->execute($tokens);
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Get Telegram API request count for current chat / message
*
* @param int|string|null $chat_id
* @param string|null $inline_message_id
*
* @return array|bool Array containing TOTAL and CURRENT fields or false on invalid arguments
* @throws TelegramException
*/
public static function getTelegramRequestCount($chat_id = null, string $inline_message_id = null)
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('SELECT
(SELECT COUNT(DISTINCT `chat_id`) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_1) AS LIMIT_PER_SEC_ALL,
(SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_2 AND ((`chat_id` = :chat_id_1 AND `inline_message_id` IS NULL) OR (`inline_message_id` = :inline_message_id AND `chat_id` IS NULL))) AS LIMIT_PER_SEC,
(SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_minute AND `chat_id` = :chat_id_2) AS LIMIT_PER_MINUTE
');
$date = self::getTimestamp();
$date_minute = self::getTimestamp(strtotime('-1 minute'));
$sth->bindValue(':chat_id_1', $chat_id);
$sth->bindValue(':chat_id_2', $chat_id);
$sth->bindValue(':inline_message_id', $inline_message_id);
$sth->bindValue(':created_at_1', $date);
$sth->bindValue(':created_at_2', $date);
$sth->bindValue(':created_at_minute', $date_minute);
$sth->execute();
return $sth->fetch();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Insert Telegram API request in db
*
* @param string $method
* @param array $data
*
* @return bool If the insert was successful
* @throws TelegramException
*/
public static function insertTelegramRequest(string $method, array $data): bool
{
if (!self::isDbConnected()) {
return false;
}
try {
$sth = self::$pdo->prepare('INSERT INTO `' . TB_REQUEST_LIMITER . '`
(`method`, `chat_id`, `inline_message_id`, `created_at`)
VALUES
(:method, :chat_id, :inline_message_id, :created_at);
');
$chat_id = $data['chat_id'] ?? null;
$inline_message_id = $data['inline_message_id'] ?? null;
$sth->bindValue(':chat_id', $chat_id);
$sth->bindValue(':inline_message_id', $inline_message_id);
$sth->bindValue(':method', $method);
$sth->bindValue(':created_at', self::getTimestamp());
return $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
/**
* Bulk update the entries of any table
*
* @param string $table
* @param array $fields_values
* @param array $where_fields_values
*
* @return bool
* @throws TelegramException
*/
public static function update(string $table, array $fields_values, array $where_fields_values): bool
{
if (empty($fields_values) || !self::isDbConnected()) {
return false;
}
try {
// Building parts of query
$tokens = $fields = $where = [];
// Fields with values to update
foreach ($fields_values as $field => $value) {
$token = ':' . count($tokens);
$fields[] = "`{$field}` = {$token}";
$tokens[$token] = $value;
}
// Where conditions
foreach ($where_fields_values as $field => $value) {
$token = ':' . count($tokens);
$where[] = "`{$field}` = {$token}";
$tokens[$token] = $value;
}
$sql = 'UPDATE `' . $table . '` SET ' . implode(', ', $fields);
$sql .= count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : '';
return self::$pdo->prepare($sql)->execute($tokens);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
}
}
| {
"content_hash": "426957387e925904d2f50793dd196494",
"timestamp": "",
"source": "github",
"line_count": 1513,
"max_line_length": 457,
"avg_line_length": 39.72901520158625,
"alnum_prop": 0.5183829645649642,
"repo_name": "akalongman/php-telegram-bot",
"id": "545133c09e81c662efa72f139c63e498010bda53",
"size": "60411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DB.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "448471"
}
],
"symlink_target": ""
} |
package org.lwjgl.opengles;
/**
* Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/NV/NV_fbo_color_attachments.txt">NV_fbo_color_attachments</a> extension.
*
* <p>This extension increases the number of available framebuffer object color attachment points.</p>
*/
public final class NVFboColorAttachments {
/** Accepted by the {@code value} parameter of GetIntegerv. */
public static final int GL_MAX_COLOR_ATTACHMENTS_NV = 0x8CDF;
/** Accepted by the {@code attachment} parameter of FramebufferRenderbuffer, FramebufferTexture2D and GetFramebufferAttachmentParameteriv. */
public static final int
GL_COLOR_ATTACHMENT0_NV = 0x8CE0,
GL_COLOR_ATTACHMENT1_NV = 0x8CE1,
GL_COLOR_ATTACHMENT2_NV = 0x8CE2,
GL_COLOR_ATTACHMENT3_NV = 0x8CE3,
GL_COLOR_ATTACHMENT4_NV = 0x8CE4,
GL_COLOR_ATTACHMENT5_NV = 0x8CE5,
GL_COLOR_ATTACHMENT6_NV = 0x8CE6,
GL_COLOR_ATTACHMENT7_NV = 0x8CE7,
GL_COLOR_ATTACHMENT8_NV = 0x8CE8,
GL_COLOR_ATTACHMENT9_NV = 0x8CE9,
GL_COLOR_ATTACHMENT10_NV = 0x8CEA,
GL_COLOR_ATTACHMENT11_NV = 0x8CEB,
GL_COLOR_ATTACHMENT12_NV = 0x8CEC,
GL_COLOR_ATTACHMENT13_NV = 0x8CED,
GL_COLOR_ATTACHMENT14_NV = 0x8CEE,
GL_COLOR_ATTACHMENT15_NV = 0x8CEF;
private NVFboColorAttachments() {}
} | {
"content_hash": "d11e2e5e5fda4098592edb033b79bd18",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 156,
"avg_line_length": 36.371428571428574,
"alnum_prop": 0.7423409269442263,
"repo_name": "MatthijsKamstra/haxejava",
"id": "a11a5769689f3fe46df0234e6f6abec41180cfdd",
"size": "1406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "04lwjgl/code/lwjgl/org/lwjgl/opengles/NVFboColorAttachments.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "122"
},
{
"name": "Haxe",
"bytes": "1163"
},
{
"name": "JavaScript",
"bytes": "724"
},
{
"name": "PHP",
"bytes": "25278"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/security/privateca/v1beta1/service.proto
package com.google.cloud.security.privateca.v1beta1;
public interface CreateCertificateAuthorityRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.security.privateca.v1beta1.CreateCertificateAuthorityRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [CertificateAuthorities][google.cloud.security.privateca.v1beta1.CertificateAuthority], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [CertificateAuthorities][google.cloud.security.privateca.v1beta1.CertificateAuthority], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`
* </pre>
*
* <code>string certificate_authority_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The certificateAuthorityId.
*/
java.lang.String getCertificateAuthorityId();
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`
* </pre>
*
* <code>string certificate_authority_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for certificateAuthorityId.
*/
com.google.protobuf.ByteString getCertificateAuthorityIdBytes();
/**
*
*
* <pre>
* Required. A [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority] with initial field values.
* </pre>
*
* <code>
* .google.cloud.security.privateca.v1beta1.CertificateAuthority certificate_authority = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the certificateAuthority field is set.
*/
boolean hasCertificateAuthority();
/**
*
*
* <pre>
* Required. A [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority] with initial field values.
* </pre>
*
* <code>
* .google.cloud.security.privateca.v1beta1.CertificateAuthority certificate_authority = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The certificateAuthority.
*/
com.google.cloud.security.privateca.v1beta1.CertificateAuthority getCertificateAuthority();
/**
*
*
* <pre>
* Required. A [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority] with initial field values.
* </pre>
*
* <code>
* .google.cloud.security.privateca.v1beta1.CertificateAuthority certificate_authority = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.security.privateca.v1beta1.CertificateAuthorityOrBuilder
getCertificateAuthorityOrBuilder();
/**
*
*
* <pre>
* Optional. An ID to identify requests. Specify a unique request ID so that if you must
* retry your request, the server will know to ignore the request if it has
* already been completed. The server will guarantee that for at least 60
* minutes since the first request.
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The requestId.
*/
java.lang.String getRequestId();
/**
*
*
* <pre>
* Optional. An ID to identify requests. Specify a unique request ID so that if you must
* retry your request, the server will know to ignore the request if it has
* already been completed. The server will guarantee that for at least 60
* minutes since the first request.
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for requestId.
*/
com.google.protobuf.ByteString getRequestIdBytes();
}
| {
"content_hash": "2f65344c0ef162373a75bff4ce38fa15",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 135,
"avg_line_length": 34.89873417721519,
"alnum_prop": 0.6875226695683714,
"repo_name": "googleapis/java-security-private-ca",
"id": "15e0c27fb250fea8c248b6fa88ee623a3cc66e98",
"size": "6108",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "proto-google-cloud-security-private-ca-v1beta1/src/main/java/com/google/cloud/security/privateca/v1beta1/CreateCertificateAuthorityRequestOrBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "9322366"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "22223"
}
],
"symlink_target": ""
} |
using System.Data.Entity;
using Models.Initializers;
namespace Models
{
public class AllModelsContext : DbContext
{
public AllModelsContext() : base("AllModelsContext")
{
var ensureDllIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
Database.SetInitializer<AllModelsContext>(new TestDataDbInitializer());
}
public DbSet<Furniture> FurnitureDb { get; set; }
public DbSet<Supplier> SupplierDb { get; set; }
public DbSet<WebEquipment> WebEquipmentDb { get; set; }
public DbSet<TypeOfWebEquipment> TypeOfWebEquipmentDb { get; set; }
public DbSet<FurnitureLocation> FurnitureLocationDb { get; set; }
public DbSet<Workspace> WorkspaceDb { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using Fluent API here
base.OnModelCreating(modelBuilder);
}
}
}
| {
"content_hash": "42f8b0698a5d747007e4ab787ae6de4a",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 94,
"avg_line_length": 29.38235294117647,
"alnum_prop": 0.6646646646646647,
"repo_name": "Manicca/Interiora",
"id": "cf4704875f0374f3f4768240371f84acff4a829e",
"size": "1001",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Interiora/Models/AllModelsContext.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "108532"
}
],
"symlink_target": ""
} |
#ifndef CARTOGRAPHER_ROS_GOOGLE_CARTOGRAPHER_SRC_MSG_CONVERSION_H_
#define CARTOGRAPHER_ROS_GOOGLE_CARTOGRAPHER_SRC_MSG_CONVERSION_H_
#include "cartographer/common/port.h"
#include "cartographer/kalman_filter/pose_tracker.h"
#include "cartographer/sensor/point_cloud.h"
#include "cartographer/sensor/proto/sensor.pb.h"
#include "cartographer/transform/rigid_transform.h"
#include "geometry_msgs/Pose.h"
#include "geometry_msgs/Transform.h"
#include "geometry_msgs/TransformStamped.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl_conversions/pcl_conversions.h"
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/LaserScan.h"
#include "sensor_msgs/MultiEchoLaserScan.h"
#include "sensor_msgs/PointCloud2.h"
namespace cartographer_ros {
// Returns a laser scan consisting of the first echo of each beam.
sensor_msgs::LaserScan ToLaserScan(
int64 timestamp, const string& frame_id,
const ::cartographer::sensor::proto::LaserScan& laser_scan);
sensor_msgs::MultiEchoLaserScan ToMultiEchoLaserScanMessage(
int64 timestamp, const string& frame_id,
const ::cartographer::sensor::proto::LaserScan& laser_scan);
sensor_msgs::PointCloud2 ToPointCloud2Message(
int64 timestamp, const string& frame_id,
const ::cartographer::sensor::PointCloud& point_cloud);
sensor_msgs::PointCloud2 ToPointCloud2Message(
int64 timestamp, const string& frame_id,
const ::cartographer::sensor::proto::LaserFan& laser_fan);
geometry_msgs::Transform ToGeometryMsgTransform(
const ::cartographer::transform::Rigid3d& rigid3d);
geometry_msgs::Pose ToGeometryMsgPose(
const ::cartographer::transform::Rigid3d& rigid3d);
::cartographer::sensor::proto::LaserScan ToCartographer(
const sensor_msgs::LaserScan& msg);
::cartographer::sensor::proto::LaserScan ToCartographer(
const sensor_msgs::MultiEchoLaserScan& msg);
::cartographer::sensor::proto::LaserFan ToCartographer(
const pcl::PointCloud<pcl::PointXYZ>& pcl_points);
::cartographer::transform::Rigid3d ToRigid3d(
const geometry_msgs::TransformStamped& transform);
::cartographer::transform::Rigid3d ToRigid3d(const geometry_msgs::Pose& pose);
Eigen::Vector3d ToEigen(const geometry_msgs::Vector3& vector3);
Eigen::Quaterniond ToEigen(const geometry_msgs::Quaternion& quaternion);
::cartographer::kalman_filter::PoseCovariance ToPoseCovariance(
const boost::array<double, 36>& covariance);
} // namespace cartographer_ros
#endif // CARTOGRAPHER_ROS_GOOGLE_CARTOGRAPHER_SRC_MSG_CONVERSION_H_
| {
"content_hash": "2184aa71b46b5f00e4d86cfb533e7d79",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 78,
"avg_line_length": 35.98571428571429,
"alnum_prop": 0.7717348154029376,
"repo_name": "af-silva/cartographer_ros",
"id": "b3d97701466c848280a5750d577a314fe0424f58",
"size": "3127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cartographer_ros/include/cartographer_ros/msg_conversion.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "124614"
},
{
"name": "CMake",
"bytes": "21673"
},
{
"name": "GLSL",
"bytes": "1733"
},
{
"name": "Lua",
"bytes": "14905"
},
{
"name": "Python",
"bytes": "1187"
},
{
"name": "Shell",
"bytes": "5664"
}
],
"symlink_target": ""
} |
package org.apache.polygene.library.sql.generator;
import org.apache.polygene.library.sql.generator.vendor.PostgreSQLVendor;
import org.apache.polygene.library.sql.generator.vendor.SQLVendor;
import org.apache.polygene.library.sql.generator.vendor.SQLVendorProvider;
/**
* @author Stanislav Muhametsin
*/
public class PostgreSQLDataDefinitionTest extends AbstractDataDefinitionTest
{
@Override
protected SQLVendor loadVendor()
throws Exception
{
return SQLVendorProvider.createVendor( PostgreSQLVendor.class );
}
}
| {
"content_hash": "22cb879837a2c46b8d70c29d90090825",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 76,
"avg_line_length": 29.05263157894737,
"alnum_prop": 0.7844202898550725,
"repo_name": "apache/zest-qi4j",
"id": "0a4a0f8b2ecfb57e82f5d6f3495d1fe998089e6d",
"size": "1172",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libraries/sql-generator/src/test/java/org/apache/polygene/library/sql/generator/PostgreSQLDataDefinitionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "46292"
},
{
"name": "Groovy",
"bytes": "21752"
},
{
"name": "HTML",
"bytes": "246264"
},
{
"name": "Java",
"bytes": "6969784"
},
{
"name": "JavaScript",
"bytes": "19790"
},
{
"name": "Python",
"bytes": "6440"
},
{
"name": "Scala",
"bytes": "8606"
},
{
"name": "Shell",
"bytes": "1233"
},
{
"name": "XSLT",
"bytes": "70993"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Thu Oct 13 19:29:18 UTC 2016 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class liquibase.integration.ant.DatabaseRollbackTask (Liquibase Core 3.5.3 API)
</TITLE>
<META NAME="date" CONTENT="2016-10-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class liquibase.integration.ant.DatabaseRollbackTask (Liquibase Core 3.5.3 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../liquibase/integration/ant/DatabaseRollbackTask.html" title="class in liquibase.integration.ant"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?liquibase/integration/ant//class-useDatabaseRollbackTask.html" target="_top"><B>FRAMES</B></A>
<A HREF="DatabaseRollbackTask.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>liquibase.integration.ant.DatabaseRollbackTask</B></H2>
</CENTER>
No usage of liquibase.integration.ant.DatabaseRollbackTask
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../liquibase/integration/ant/DatabaseRollbackTask.html" title="class in liquibase.integration.ant"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?liquibase/integration/ant//class-useDatabaseRollbackTask.html" target="_top"><B>FRAMES</B></A>
<A HREF="DatabaseRollbackTask.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2016 <a href="http://www.liquibase.org">Liquibase.org</a>. All rights reserved.
</BODY>
</HTML>
| {
"content_hash": "afb79df2a2e7fa5dec89d06d7e1c9e28",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 225,
"avg_line_length": 42.55862068965517,
"alnum_prop": 0.6282612218441096,
"repo_name": "myapos/ClientManagerSpringBoot",
"id": "233dbbe01167e1f2e5a809cefb3d1844aa940fb4",
"size": "6171",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "database_schemas/liquibase-3.5.3-bin/sdk/javadoc/liquibase/integration/ant/class-use/DatabaseRollbackTask.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7142"
},
{
"name": "CSS",
"bytes": "28980"
},
{
"name": "HTML",
"bytes": "23194"
},
{
"name": "Java",
"bytes": "83010"
},
{
"name": "JavaScript",
"bytes": "854753"
},
{
"name": "Shell",
"bytes": "2956"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Mar 03 10:44:38 EST 2014 -->
<title>Uses of Class org.hibernate.metamodel.source.annotations.attribute.AssociationAttribute (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.hibernate.metamodel.source.annotations.attribute.AssociationAttribute (Hibernate JavaDocs)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/hibernate/metamodel/source/annotations/attribute/class-use/AssociationAttribute.html" target="_top">Frames</a></li>
<li><a href="AssociationAttribute.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.hibernate.metamodel.source.annotations.attribute.AssociationAttribute" class="title">Uses of Class<br>org.hibernate.metamodel.source.annotations.attribute.AssociationAttribute</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.hibernate.metamodel.source.annotations.attribute">org.hibernate.metamodel.source.annotations.attribute</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.hibernate.metamodel.source.annotations.entity">org.hibernate.metamodel.source.annotations.entity</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.hibernate.metamodel.source.annotations.attribute">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a> in <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/package-summary.html">org.hibernate.metamodel.source.annotations.attribute</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/package-summary.html">org.hibernate.metamodel.source.annotations.attribute</a> that return <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a></code></td>
<td class="colLast"><span class="strong">AssociationAttribute.</span><code><strong><a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html#createAssociationAttribute(java.lang.String, java.lang.Class, org.hibernate.metamodel.source.annotations.attribute.AttributeNature, java.lang.String, java.util.Map, org.hibernate.metamodel.source.annotations.entity.EntityBindingContext)">createAssociationAttribute</a></strong>(<a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name,
<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html?is-external=true" title="class or interface in java.lang">Class</a><?> attributeType,
<a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AttributeNature.html" title="enum in org.hibernate.metamodel.source.annotations.attribute">AttributeNature</a> attributeNature,
<a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> accessType,
<a href="http://download.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><org.jboss.jandex.DotName,<a href="http://download.oracle.com/javase/6/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><org.jboss.jandex.AnnotationInstance>> annotations,
<a href="../../../../../../../org/hibernate/metamodel/source/annotations/entity/EntityBindingContext.html" title="class in org.hibernate.metamodel.source.annotations.entity">EntityBindingContext</a> context)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/package-summary.html">org.hibernate.metamodel.source.annotations.attribute</a> with parameters of type <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/ToOneAttributeSourceImpl.html#ToOneAttributeSourceImpl(org.hibernate.metamodel.source.annotations.attribute.AssociationAttribute)">ToOneAttributeSourceImpl</a></strong>(<a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a> associationAttribute)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.hibernate.metamodel.source.annotations.entity">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a> in <a href="../../../../../../../org/hibernate/metamodel/source/annotations/entity/package-summary.html">org.hibernate.metamodel.source.annotations.entity</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/hibernate/metamodel/source/annotations/entity/package-summary.html">org.hibernate.metamodel.source.annotations.entity</a> that return types with arguments of type <a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html?is-external=true" title="class or interface in java.lang">Iterable</a><<a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">AssociationAttribute</a>></code></td>
<td class="colLast"><span class="strong">ConfiguredClass.</span><code><strong><a href="../../../../../../../org/hibernate/metamodel/source/annotations/entity/ConfiguredClass.html#getAssociationAttributes()">getAssociationAttributes</a></strong>()</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/hibernate/metamodel/source/annotations/attribute/AssociationAttribute.html" title="class in org.hibernate.metamodel.source.annotations.attribute">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/hibernate/metamodel/source/annotations/attribute/class-use/AssociationAttribute.html" target="_top">Frames</a></li>
<li><a href="AssociationAttribute.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2001-2014 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.</small></p>
</body>
</html>
| {
"content_hash": "faeeeddc5858045678a1095b1bfddb50",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 625,
"avg_line_length": 63.78350515463917,
"alnum_prop": 0.6866817520607725,
"repo_name": "serious6/HibernateSimpleProject",
"id": "926f16ee34a20925e09f463933ad4193e66eca57",
"size": "12374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadoc/hibernate_Doc/org/hibernate/metamodel/source/annotations/attribute/class-use/AssociationAttribute.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12560"
},
{
"name": "Java",
"bytes": "15329"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>finger-tree: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.14.1 / finger-tree - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
finger-tree
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-06-02 20:58:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-02 20:58:29 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.14.1 Formal proof management system
dune 3.2.0 Fast, portable, and opinionated build system
ocaml 4.13.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.13.1 Official release 4.13.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/finger-tree"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/FingerTree"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: data structures" "keyword: dependent types" "keyword: Finger Trees" "category: Computer Science/Data Types and Data Structures" "date: 2009-02" ]
authors: [ "Matthieu Sozeau <[email protected]> [http://mattam.org]" ]
bug-reports: "https://github.com/coq-contribs/finger-tree/issues"
dev-repo: "git+https://github.com/coq-contribs/finger-tree.git"
synopsis: "Dependent Finger Trees"
description: """
http://mattam.org/research/russell/fingertrees.en.html
A verified generic implementation of Finger Trees"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/finger-tree/archive/v8.7.0.tar.gz"
checksum: "md5=65bc1765ca51e147bcbd410b0f4c88b0"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-finger-tree.8.7.0 coq.8.14.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.14.1).
The following dependencies couldn't be met:
- coq-finger-tree -> coq < 8.8~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-finger-tree.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "9ddbb7433b951bed4904607a40fcd5f7",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 213,
"avg_line_length": 43,
"alnum_prop": 0.5441860465116279,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "9f7b58b4b9aa2e25aaf39bce0026834239f18843",
"size": "7120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.13.1-2.0.10/released/8.14.1/finger-tree/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version='1.1' encoding='UTF-8'?>
<project>
<actions/>
<description>Test run of data resource load for sandbox test environment</description>
<keepDependencies>false</keepDependencies>
<properties>
<jenkins.model.BuildDiscarderProperty>
<strategy class="hudson.tasks.LogRotator">
<daysToKeep>-1</daysToKeep>
<numToKeep>10</numToKeep>
<artifactDaysToKeep>-1</artifactDaysToKeep>
<artifactNumToKeep>-1</artifactNumToKeep>
</strategy>
</jenkins.model.BuildDiscarderProperty>
<org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty/>
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
<hudson.model.StringParameterDefinition>
<name>uid</name>
<description>Temporary data resource id</description>
<defaultValue>drt0000</defaultValue>
<trim>true</trim>
</hudson.model.StringParameterDefinition>
<hudson.model.StringParameterDefinition>
<name>apikey</name>
<description>API key to pass to the collectory</description>
<defaultValue>{{ registry_api_key }}</defaultValue>
<trim>false</trim>
</hudson.model.StringParameterDefinition>
<hudson.model.StringParameterDefinition>
<name>collectory</name>
<description>Collectory URL</description>
<defaultValue>{{ collectory_url }}</defaultValue>
<trim>false</trim>
</hudson.model.StringParameterDefinition>
<hudson.model.StringParameterDefinition>
<name>dr</name>
<description>Permanent data resource uid</description>
<defaultValue>dr0000</defaultValue>
<trim>false</trim>
</hudson.model.StringParameterDefinition>
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>
</properties>
<builders>
<hudson.tasks.Shell>
<command>#!/bin/sh
echo "Sandbox import called with the following properties uid=${uid} dr=${dr} apikey=${apikey} collectory=${collectory}"
biocache load -t "$dr"
</command>
</hudson.tasks.Shell>
</builders>
<triggers/>
<authToken>{{ jenkins_token }}</authToken>
<disabled>false</disabled>
</project> | {
"content_hash": "9ca0ad5c4770f04dad14f6bcd994f101",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 120,
"avg_line_length": 46.32142857142857,
"alnum_prop": 0.5875096376252892,
"repo_name": "AtlasOfLivingAustralia/ala-install",
"id": "61af15f6b70517b9aab968c295953b7bb7b318df",
"size": "2594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ansible/roles/jenkins-skeleton/templates/Sandbox Test Run.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "52562"
},
{
"name": "Groovy",
"bytes": "48862"
},
{
"name": "HTML",
"bytes": "34639"
},
{
"name": "JavaScript",
"bytes": "13"
},
{
"name": "Jinja",
"bytes": "211221"
},
{
"name": "Makefile",
"bytes": "814"
},
{
"name": "Python",
"bytes": "77723"
},
{
"name": "Ruby",
"bytes": "12789"
},
{
"name": "Shell",
"bytes": "54368"
}
],
"symlink_target": ""
} |
using System;
namespace anime_downloader.Patch.Services.Interface
{
/// <summary>
/// Handle all version updates.
/// </summary>
public interface IPatchService
{
/// <summary>
/// The output stream.
/// </summary>
Action<string> Output { get; set; }
/// <summary>
/// Make any necessary changes to successfuly go from previous -> current.
/// </summary>
(bool updated, bool failed) Patch(Version previous, Version current);
}
} | {
"content_hash": "272dba03f2a5941a6996159d36229a77",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 86,
"avg_line_length": 26.5,
"alnum_prop": 0.5679245283018868,
"repo_name": "dukemiller/anime-downloader",
"id": "b0627452931b41da2237e38d51e965df38a96794",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "anime-downloader.Patch/Services/Interface/IPatchService.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "463857"
}
],
"symlink_target": ""
} |
function MasyuController(problems) {
this.option = {};
this.option.outerMargin = 20;
this.gridController = new GridController();
this.isFinished = false;
this.problems = problems;
this.setProblemId(0);
this.setZoom(3);
}
MasyuController.prototype.setView = function (view) {
this.view = view;
this.view.setField(this.field);
this.view.setOption(this.option);
this.view.adjustCanvasSize();
this.view.drawAll();
}
MasyuController.prototype.setZoom = function (z) {
this.zoom = z;
// parameters for SlitherlinkView
this.option.gridLineWidth = z * 1;
this.option.loopLineWidth = z * 1;
this.option.cellSize = z * 10;
this.option.blankXSize = z * 1.5;
// parameters for GridController
this.gridController.offsetX = this.option.outerMargin + this.option.gridLineWidth + this.option.cellSize / 2;
this.gridController.offsetY = this.option.outerMargin + this.option.gridLineWidth + this.option.cellSize / 2;
this.gridController.lineWidth = this.option.loopLineWidth;
this.gridController.cellSize = this.option.cellSize;
this.gridController.vertexThresholdDistance = z * 5;
this.gridController.edgeThresholdDistance = z * 3;
this.gridController.clickThresholdDistance = z * 2;
}
MasyuController.prototype.setProblemSet = function (problems) {
this.problems = problems;
this.setProblemId(0);
}
MasyuController.prototype.setProblemId = function (idx) {
this.isFinished = false;
this.undoHistory = [];
this.redoHistory = [];
this.problemId = idx;
this.field = new MasyuField(this.problems[idx]);
this.gridController.setField(this.field.getInternalGrid());
if (this.view) {
this.view.setField(this.field);
this.view.adjustCanvasSize();
this.view.drawAll();
}
}
MasyuController.prototype.getProblemId = function () {
return this.problemId;
}
MasyuController.prototype.getNumberOfProblems = function () {
return this.problems.length;
}
MasyuController.prototype.performUpdate = function (edges) {
this.isFinished = this.field.isFinished();
if (this.view) {
for (var i = 0; i < edges.length; ++i) {
this.view.drawEdge(edges[i].x, edges[i].y);
}
this.view.drawIfComplete();
}
}
MasyuController.prototype.mouseDown = function (x, y) {
this.performUpdate(this.gridController.mouseDown(x, y, this.isFinished));
}
MasyuController.prototype.mouseMove = function (x, y) {
this.performUpdate(this.gridController.mouseMove(x, y, this.isFinished));
}
MasyuController.prototype.mouseUp = function (x, y) {
this.performUpdate(this.gridController.mouseUp(x, y, this.isFinished));
}
MasyuController.prototype.performUndo = function () {
this.performUpdate(this.gridController.performUndo());
}
MasyuController.prototype.performUndoAll = function () {
this.performUpdate(this.gridController.performUndoAll());
}
MasyuController.prototype.performRedo = function () {
this.performUpdate(this.gridController.performRedo());
}
MasyuController.prototype.performRedoAll = function () {
this.performUpdate(this.gridController.performRedoAll());
}
MasyuController.prototype.zoomOut = function () {
if (this.zoom <= 3) return;
this.setZoom(this.zoom - 1);
if (this.view) {
this.view.adjustCanvasSize();
this.view.drawAll();
}
}
MasyuController.prototype.zoomIn = function () {
this.setZoom(this.zoom + 1);
if (this.view) {
this.view.adjustCanvasSize();
this.view.drawAll();
}
}
MasyuController.prototype.previousProblem = function () {
if (this.problemId == 0) this.problemId = this.problems.length - 1;
else this.problemId -= 1;
this.setProblemId(this.problemId);
}
MasyuController.prototype.nextProblem = function () {
if (this.problemId == this.problems.length - 1) this.problemId = 0;
else this.problemId += 1;
this.setProblemId(this.problemId);
}
| {
"content_hash": "de922a774a4d8624b22d07d0a403c9a5",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 113,
"avg_line_length": 33.71900826446281,
"alnum_prop": 0.6762254901960785,
"repo_name": "semiexp/penciloid-player",
"id": "cc818cfaaad02dbb8b8bb0716f4bb127c3b7125d",
"size": "4080",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/ms_controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6135"
},
{
"name": "JavaScript",
"bytes": "107345"
}
],
"symlink_target": ""
} |
""" standard """
from threatconnect import ApiProperties
from threatconnect.RequestObject import RequestObject
from threatconnect.SecurityLabelObject import parse_security_label, SecurityLabelObject
""" custom """
from threatconnect.ErrorCodes import ErrorCodes
def parse_attribute(attribute_dict, container):
""" """
# store the resource object in the master resource object list
# roi = resource_obj.add_master_resource_obj(AttributeObject(), attribute_dict['id'])
# retrieve the resource object and update data
# attribute = resource_obj.get_resource_by_identity(roi)
attribute = AttributeObject(container)
#
# standard values
#
attribute.set_date_added(attribute_dict['dateAdded'])
attribute.set_displayed(attribute_dict['displayed'])
attribute.set_id(attribute_dict['id'])
attribute.set_last_modified(attribute_dict['lastModified'])
attribute.set_type(attribute_dict['type'])
attribute.set_value(attribute_dict['value'])
return attribute
class AttributeObject(object):
__slots__ = (
'_date_added',
'_displayed',
'_id',
'_last_modified',
'_required_attrs',
'_type',
'_value',
'_validated',
'_writable_attrs',
'_resource_properties',
'_security_labels',
'_container'
)
def __init__(self, container):
self._resource_properties = ApiProperties.api_properties['ATTRIBUTES']['properties']
self._date_added = None
self._displayed = None
self._id = None
self._last_modified = None
self._required_attrs = ['type', 'value']
self._type = None
self._value = None
self._security_labels = []
self._container = container
self._writable_attrs = {
'_displayed': 'set_displayed',
'_type': 'set_type',
'_value': 'set_value'
}
# validation
self._validated = False
#
# unicode
#
@staticmethod
def _uni(data):
""" """
if isinstance(data, (int, list, dict)):
return data
elif isinstance(data, unicode):
return unicode(data.encode('utf-8').strip(), errors='ignore') # re-encode poorly encoded unicode
elif not isinstance(data, unicode):
return unicode(data, 'utf-8', errors='ignore')
else:
return data
""" shared attribute methods """
#
# date_added
#
@property
def date_added(self):
""" """
return self._date_added
def set_date_added(self, data):
"""Read-Only attribute metadata"""
self._date_added = data
#
# displayed
#
@property
def displayed(self):
""" """
return self._displayed
def set_displayed(self, data):
"""Read-Write attribute metadata"""
self._displayed = data
#
# id
#
@property
def id(self):
""" """
return self._id
def set_id(self, data):
"""Read-Only attribute metadata"""
if isinstance(data, int):
self._id = data
else:
raise AttributeError(ErrorCodes.e10020.value.format(data))
#
# last_modified
#
@property
def last_modified(self):
""" """
return self._last_modified
def set_last_modified(self, data):
"""Read-Only attribute metadata"""
self._last_modified = data
#
# type
#
@property
def type(self):
""" """
return self._type
def set_type(self, data):
"""Read-Write attribute metadata"""
self._type = self._uni(data)
#
# value
#
@property
def value(self):
""" """
return self._value
def set_value(self, data):
"""Read-Write attribute metadata"""
self._value = self._uni(data)
#
# validated
#
@property
def validated(self):
""" """
return self._validated
def validate(self):
""" """
for required in self._required_attrs:
if getattr(self, required) is None:
self._validated = False
return
self._validated = True
def load_security_labels(self):
""" retrieve attributes for this indicator """
prop = self._resource_properties['load_security_labels']
ro = RequestObject()
ro.set_description('load security labels for attribute {0} of object {1}'.format(self.id, self._container.id))
ro.set_http_method(prop['http_method'])
ro.set_owner_allowed(prop['owner_allowed'])
resource_uri = self._container._resource_properties['id']['uri']
try:
resource_uri = resource_uri.format(self._container.indicator)
except AttributeError:
resource_uri = resource_uri.format(self._container.id)
ro.set_request_uri(prop['uri'].format(resource_uri, self.id))
ro.set_resource_pagination(prop['pagination'])
api_response = self._container._tc.api_request(ro)
if api_response.headers['content-type'] == 'application/json':
api_response_dict = api_response.json()
if api_response_dict['status'] == 'Success':
self._security_labels = []
data = api_response_dict['data']['securityLabel']
for item in data:
self.__add_security_label(parse_security_label(item)) # add to main resource object
def delete_security_label(self, security_label_name):
""" retrieve attributes for this indicator """
prop = self._resource_properties['delete_security_label']
ro = RequestObject()
ro.set_description('deleting security label {0} for attribute {1} of object {2}'.format(security_label_name,
self.id,
self._container.id))
ro.set_http_method(prop['http_method'])
ro.set_owner_allowed(prop['owner_allowed'])
resource_uri = self._container._resource_properties['id']['uri']
try:
resource_uri = resource_uri.format(self._container.indicator)
except AttributeError:
resource_uri = resource_uri.format(self._container.id)
ro.set_request_uri(prop['uri'].format(resource_uri, self.id, security_label_name))
ro.set_resource_pagination(prop['pagination'])
self._container._resource_container.add_commit_queue(self._container.id, ro)
def __add_security_label(self, security_label):
self._security_labels.append(security_label)
def add_security_label(self, security_label_name):
""" retrieve attributes for this indicator """
prop = self._resource_properties['add_security_label']
ro = RequestObject()
ro.set_description('deleting security label {0} for attribute {1} of object {2}'.format(security_label_name,
self.id,
self._container.id))
ro.set_http_method(prop['http_method'])
ro.set_owner_allowed(prop['owner_allowed'])
resource_uri = self._container._resource_properties['id']['uri']
try:
resource_uri = resource_uri.format(self._container.indicator)
except AttributeError:
resource_uri = resource_uri.format(self._container.id)
ro.set_request_uri(prop['uri'].format(resource_uri, self.id, security_label_name))
ro.set_resource_pagination(prop['pagination'])
callback = lambda status: self.__failed_add_security_label(security_label_name)
ro.set_failure_callback(callback)
self._container._resource_container.add_commit_queue(self._container.id, ro)
security_label = SecurityLabelObject()
security_label.set_name(security_label_name)
self.__add_security_label(security_label)
def __failed_add_security_label(self, security_label_name):
for security_label in self._security_labels:
if security_label.name == security_label_name:
self._security_labels.remove(security_label)
break
#
# security_labels
#
@property
def security_labels(self):
""" """
return self._security_labels
#
# add print method
#
def __str__(self):
"""allow object to be displayed with print"""
printable_string = '\n{0!s:_^80}\n'.format('Attribute Object Properties')
#
# retrievable methods
#
printable_string += '{0!s:40}\n'.format('Retrievable Methods')
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('id', self.id))
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('type', self.type))
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('value', self.value))
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('displayed', self.displayed))
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('date_added', self.date_added))
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('last_modified', self.last_modified))
return printable_string
| {
"content_hash": "c42a7080a611e99c73a1bb21b0b1468a",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 118,
"avg_line_length": 33.78928571428571,
"alnum_prop": 0.5691787337490751,
"repo_name": "percipient/threatconnect-python",
"id": "ad3dc1638a0e049da8434f73c1921e7d62cc8906",
"size": "9461",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "threatconnect/AttributeObject.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "381902"
}
],
"symlink_target": ""
} |
#include <boost/container/pmr/global_resource.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/intrusive/detail/math.hpp>
#include "derived_from_memory_resource.hpp"
#include "memory_resource_logger.hpp"
using namespace boost::container::pmr;
template<class PoolResource>
struct derived_from_pool_resource
: public PoolResource
{
derived_from_pool_resource(const pool_options& opts, memory_resource* upstream)
: PoolResource(opts, upstream)
{}
explicit derived_from_pool_resource(memory_resource *p)
: PoolResource(p)
{}
explicit derived_from_pool_resource(const pool_options &opts)
: PoolResource(opts)
{}
derived_from_pool_resource()
: PoolResource()
{}
using PoolResource::do_allocate;
using PoolResource::do_deallocate;
using PoolResource::do_is_equal;
};
template<class PoolResource>
void test_default_constructor()
{
//With default options/resource
{
derived_from_memory_resource dmr;
dmr.reset();
PoolResource m;
//test postconditions
BOOST_TEST(m.upstream_resource() == get_default_resource());
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_default_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
}
template<class PoolResource>
void test_upstream_constructor()
{
//With a resource, default options
{
derived_from_memory_resource dmr;
dmr.reset();
PoolResource m(&dmr);
//test postconditions
BOOST_TEST(m.upstream_resource() == &dmr);
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_default_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
}
template<class PoolResource>
void test_options_constructor()
{
//Default options
{
memory_resource_logger mrl;
BOOST_TEST(mrl.m_info.size() == 0u);
set_default_resource(&mrl);
pool_options opts;
PoolResource m(opts);
//test postconditions
BOOST_TEST(m.upstream_resource() == get_default_resource());
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_default_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(mrl.m_info.size() == 0u);
}
//Too large option values
{
memory_resource_logger mrl;
BOOST_TEST(mrl.m_info.size() == 0u);
set_default_resource(&mrl);
pool_options opts;
opts.max_blocks_per_chunk = pool_options_default_max_blocks_per_chunk+1;
opts.largest_required_pool_block = pool_options_default_largest_required_pool_block+1;
PoolResource m(opts);
//test postconditions
BOOST_TEST(m.upstream_resource() == get_default_resource());
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_default_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(mrl.m_info.size() == 0u);
}
//Too small option values
{
memory_resource_logger mrl;
BOOST_TEST(mrl.m_info.size() == 0u);
set_default_resource(&mrl);
pool_options opts;
opts.largest_required_pool_block = pool_options_minimum_largest_required_pool_block-1u;
PoolResource m(opts);
//test postconditions
BOOST_TEST(m.upstream_resource() == get_default_resource());
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_minimum_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(mrl.m_info.size() == 0u);
}
//In range option values
{
memory_resource_logger mrl;
BOOST_TEST(mrl.m_info.size() == 0u);
set_default_resource(&mrl);
pool_options opts;
opts.max_blocks_per_chunk = pool_options_default_max_blocks_per_chunk;
opts.largest_required_pool_block = pool_options_minimum_largest_required_pool_block;
PoolResource m(opts);
//test postconditions
BOOST_TEST(m.upstream_resource() == get_default_resource());
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_minimum_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(mrl.m_info.size() == 0u);
}
}
template<class PoolResource>
void test_options_upstream_constructor()
{
//Default options
{
derived_from_memory_resource dmr;
dmr.reset();
pool_options opts;
PoolResource m(opts, &dmr);
//test postconditions
BOOST_TEST(m.upstream_resource() == &dmr);
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_default_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
//Too large option values
{
derived_from_memory_resource dmr;
dmr.reset();
pool_options opts;
opts.max_blocks_per_chunk = pool_options_default_max_blocks_per_chunk+1;
opts.largest_required_pool_block = pool_options_default_largest_required_pool_block+1;
PoolResource m(opts, &dmr);
//test postconditions
BOOST_TEST(m.upstream_resource() == &dmr);
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_default_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
//Too small option values
{
derived_from_memory_resource dmr;
dmr.reset();
pool_options opts;
opts.largest_required_pool_block = pool_options_minimum_largest_required_pool_block-1u;
PoolResource m(opts, &dmr);
//test postconditions
BOOST_TEST(m.upstream_resource() == &dmr);
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
BOOST_TEST(m.options().largest_required_pool_block == pool_options_minimum_largest_required_pool_block);
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
//In range option values
{
derived_from_memory_resource dmr;
dmr.reset();
pool_options opts;
opts.max_blocks_per_chunk = pool_options_default_max_blocks_per_chunk;
opts.largest_required_pool_block = pool_options_minimum_largest_required_pool_block;
PoolResource m(opts, &dmr);
//test postconditions
BOOST_TEST(m.upstream_resource() == &dmr);
//max blocks is unchanged in this implementation
BOOST_TEST(m.options().max_blocks_per_chunk == pool_options_default_max_blocks_per_chunk);
//largest block is rounded to pow2
BOOST_TEST(m.options().largest_required_pool_block == bi::detail::ceil_pow2(opts.largest_required_pool_block));
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
}
template<class PoolResource>
void test_options()
{
//In range option values
{
derived_from_memory_resource dmr;
dmr.reset();
pool_options opts;
opts.max_blocks_per_chunk = pool_options_default_max_blocks_per_chunk/2u;
opts.largest_required_pool_block = (pool_options_default_largest_required_pool_block
- pool_options_minimum_largest_required_pool_block) | std::size_t(1); //guaranteed to be non power of 2.
PoolResource m(opts, &dmr);
//test postconditions
BOOST_TEST(m.upstream_resource() == &dmr);
//max blocks is unchanged in this implementation
BOOST_TEST(m.options().max_blocks_per_chunk == opts.max_blocks_per_chunk);
//largest block is rounded to pow2
BOOST_TEST(m.options().largest_required_pool_block == bi::detail::ceil_pow2(opts.largest_required_pool_block));
//test it does not allocate any memory
BOOST_TEST(dmr.do_allocate_called == false);
}
}
template<class PoolResource>
void test_do_allocate_deallocate()
{
memory_resource_logger mrl;
{
derived_from_pool_resource<PoolResource> dmbr(&mrl);
{
//First block from pool 0
dmbr.do_allocate(1, 1);
//It should allocate the pool array plus an initial block
BOOST_TEST(mrl.m_info.size() == 2u);
//Second block from pool 0
dmbr.do_allocate(1, 1);
//It should allocate again (with 2 chunks per block)
BOOST_TEST(mrl.m_info.size() == 3u);
//Third block from pool 0
dmbr.do_allocate(1, 1);
//It should NOT allocate again (previous was a 2 block chunk)
BOOST_TEST(mrl.m_info.size() == 3u);
}
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
//Allocate and deallocate from the same chunk to test block caching
{
derived_from_pool_resource<PoolResource> dmbr(&mrl);
{
//First block from pool 0
void *p = dmbr.do_allocate(1, 1);
//It should allocate the pool array plus an initial block
BOOST_TEST(mrl.m_info.size() == 2u);
//No cached, as initial blocks per chunk is 1
BOOST_TEST(dmbr.pool_cached_blocks(0u) == 0u);
//Deallocate and allocate again
dmbr.do_deallocate(p, 1, 1);
//Cached
BOOST_TEST(dmbr.pool_cached_blocks(0u) == 1u);
p = dmbr.do_allocate(1, 1);
//Reused
BOOST_TEST(dmbr.pool_cached_blocks(0u) == 0u);
//It should have NOT allocated (block reuse)
BOOST_TEST(mrl.m_info.size() == 2u);
//Allocate again 2 times (a 2 block chunk is exhausted)
void *p2 = dmbr.do_allocate(1, 1);
//1 left cached
BOOST_TEST(dmbr.pool_cached_blocks(0u) == 1u);
void *p3 = dmbr.do_allocate(1, 1);
//Cache exhausted
BOOST_TEST(dmbr.pool_cached_blocks(0u) == 0u);
//Single chunk allocation happened
BOOST_TEST(mrl.m_info.size() == 3u);
//Now deallocate all (no memory is freed, all cached)
dmbr.do_deallocate(p2, 1, 1);
dmbr.do_deallocate(p3, 1, 1);
dmbr.do_deallocate(p, 1, 1);
BOOST_TEST(dmbr.pool_cached_blocks(0u) == 3u);
BOOST_TEST(mrl.m_info.size() == 3u);
}
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
//Now test max block per chunk
{
pool_options opts;
//so after max_blocks_per_chunk*2-1 allocations, all new chunks must hold max_blocks_per_chunk blocks
opts.max_blocks_per_chunk = 32u;
derived_from_pool_resource<PoolResource> dmbr(opts, &mrl);
{
std::size_t loops = opts.max_blocks_per_chunk*2-1u;
while(loops--){
dmbr.do_allocate(1, 1);
}
//pool array + log2(max_blocks_per_chunk)+1 chunks (sizes [1, 2, 4, ...])
const std::size_t num_chunks = bi::detail::floor_log2(opts.max_blocks_per_chunk)+1u;
BOOST_TEST(mrl.m_info.size() == 1u + num_chunks);
//Next allocation should allocate max_blocks_per_chunk blocks in a chunk so max_blocks_per_chunk-1 should remain free
dmbr.do_allocate(1, 1);
BOOST_TEST(mrl.m_info.size() == 1u + num_chunks + 1u);
BOOST_TEST(dmbr.pool_cached_blocks(0u) == (opts.max_blocks_per_chunk-1u));
//Exhaust the chunk and allocate a new one, test max_blocks_per_chunk is not passed again
loops = opts.max_blocks_per_chunk;
while(loops--){
dmbr.do_allocate(1, 1);
}
BOOST_TEST(mrl.m_info.size() == 1u + num_chunks + 2u);
BOOST_TEST(dmbr.pool_cached_blocks(0u) == (opts.max_blocks_per_chunk-1u));
}
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
//Now test max block per chunk
{
pool_options opts;
//so after max_blocks_per_chunk*2-1 allocations, all new chunks must hold max_blocks_per_chunk blocks
opts.max_blocks_per_chunk = 32u;
derived_from_pool_resource<PoolResource> dmbr(opts, &mrl);
{
std::size_t loops = opts.max_blocks_per_chunk*2-1u;
while(loops--){
dmbr.do_allocate(1, 1);
}
//pool array + log2(max_blocks_per_chunk)+1 chunks (sizes [1, 2, 4, ...])
BOOST_TEST(dmbr.pool_next_blocks_per_chunk(0u) == opts.max_blocks_per_chunk);
const std::size_t num_chunks = bi::detail::floor_log2(opts.max_blocks_per_chunk)+1u;
BOOST_TEST(mrl.m_info.size() == 1u + num_chunks);
//Next allocation should allocate max_blocks_per_chunk blocks in a chunk so max_blocks_per_chunk-1 should remain free
dmbr.do_allocate(1, 1);
BOOST_TEST(dmbr.pool_next_blocks_per_chunk(0u) == opts.max_blocks_per_chunk);
BOOST_TEST(mrl.m_info.size() == 1u + num_chunks + 1u);
BOOST_TEST(dmbr.pool_cached_blocks(0u) == (opts.max_blocks_per_chunk-1u));
}
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
//Now test different pool sizes
{
pool_options opts;
//so after max_blocks_per_chunk*2-1 allocations, all new chunks must hold max_blocks_per_chunk blocks
opts.max_blocks_per_chunk = 1u;
derived_from_pool_resource<PoolResource> dmbr(opts, &mrl);
const pool_options &final_opts = dmbr.options();
//Force pool creation
dmbr.do_deallocate(dmbr.do_allocate(1, 1), 1, 1);
//pool array plus first pool's chunk allocation
BOOST_TEST(mrl.m_info.size() == 2u);
//pool count must be:
// log2(the maximum block) - log2(the minimum block) + 1. Example if minimum block is 8, and maximum 32:
// log(32) - log2(8) + 1u = 3 pools (block sizes: 8, 16, and 32)
const std::size_t minimum_size = dmbr.pool_block(0u);
const std::size_t maximum_size = final_opts.largest_required_pool_block;
BOOST_TEST(dmbr.pool_count() == (1u + bi::detail::floor_log2(maximum_size) - bi::detail::floor_log2(minimum_size)));
for(std::size_t i = 0, s = minimum_size, max = dmbr.pool_count(); i != max; ++i, s*=2){
//Except in the first pool, each cache should be empty
BOOST_TEST(dmbr.pool_cached_blocks(i) == std::size_t(i == 0));
dmbr.do_deallocate(dmbr.do_allocate(s/2+1, 1), s/2+1, 1);
dmbr.do_deallocate(dmbr.do_allocate(s-1, 1), s-1, 1);
dmbr.do_deallocate(dmbr.do_allocate(s, 1), s, 1);
//pool array plus each previous chunk allocation
BOOST_TEST(mrl.m_info.size() == (1u + i + 1u));
//as we limited max_blocks_per_chunk to 1, no cached blocks should be available except one
BOOST_TEST(dmbr.pool_cached_blocks(i) == 1u);
}
//Now test out of maximum values, which should go directly to upstream
//it should be directly deallocated.
void *p = dmbr.do_allocate(maximum_size+1, 1);
BOOST_TEST(mrl.m_info.size() == (1u + dmbr.pool_count() + 1u));
dmbr.do_deallocate(p, maximum_size+1, 1);
BOOST_TEST(mrl.m_info.size() == (1u + dmbr.pool_count()));
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
}
template<class PoolResource>
void test_do_is_equal()
{
//`this == dynamic_cast<const PoolResource*>(&other)`.
memory_resource_logger mrl;
derived_from_pool_resource<PoolResource> dmbr(&mrl);
derived_from_pool_resource<PoolResource> dmbr2(&mrl);
BOOST_TEST(true == dmbr.do_is_equal(dmbr));
BOOST_TEST(false == dmbr.do_is_equal(dmbr2));
//A different type should be always different
derived_from_memory_resource dmr;
BOOST_TEST(false == dmbr.do_is_equal(dmr));
}
template<class PoolResource>
void test_release()
{
memory_resource_logger mrl;
{
pool_options opts;
//so after max_blocks_per_chunk*2-1 allocations, all new chunks must hold max_blocks_per_chunk blocks
opts.max_blocks_per_chunk = 4u;
derived_from_pool_resource<PoolResource> dmbr(opts, &mrl);
const pool_options &final_opts = dmbr.options();
const std::size_t minimum_size = dmbr.pool_block(0u);
const std::size_t maximum_size = final_opts.largest_required_pool_block;
const std::size_t pool_count = 1u + bi::detail::floor_log2(maximum_size) - bi::detail::floor_log2(minimum_size);
std::size_t expected_memory_allocs = 0;
for(std::size_t i = 0, imax = pool_count, s = minimum_size; i != imax; s*=2, ++i){
for(std::size_t j = 0, j_max = opts.max_blocks_per_chunk*2u-1u; j != j_max; ++j){
dmbr.do_allocate(s, 1);
}
//One due to the pool array, and for each pool, log2(max_blocks_per_chunk)+1 allocations
expected_memory_allocs = 1 + (bid::floor_log2(opts.max_blocks_per_chunk) + 1u)*(i+1);
//pool array plus each previous chunk allocation
BOOST_TEST(mrl.m_info.size() == expected_memory_allocs);
}
//Now with out-of-pool sizes
for(std::size_t j = 0, j_max = opts.max_blocks_per_chunk*2u-1u; j != j_max; ++j){
dmbr.do_allocate(maximum_size+1, 1);
BOOST_TEST(mrl.m_info.size() == ++expected_memory_allocs);
}
//Now release memory and check all memory allocated through do_allocate was deallocated to upstream
dmbr.release();
BOOST_TEST(mrl.m_info.size() == 1u);
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
}
template<class PoolResource>
void test_destructor()
{
memory_resource_logger mrl;
{
pool_options opts;
//so after max_blocks_per_chunk*2-1 allocations, all new chunks must hold max_blocks_per_chunk blocks
opts.max_blocks_per_chunk = 4u;
derived_from_pool_resource<PoolResource> dmbr(opts, &mrl);
const pool_options &final_opts = dmbr.options();
const std::size_t minimum_size = dmbr.pool_block(0u);
const std::size_t maximum_size = final_opts.largest_required_pool_block;
const std::size_t pool_count = 1u + bi::detail::floor_log2(maximum_size) - bi::detail::floor_log2(minimum_size);
std::size_t expected_memory_allocs = 0;
for(std::size_t i = 0, imax = pool_count, s = minimum_size; i != imax; s*=2, ++i){
for(std::size_t j = 0, j_max = opts.max_blocks_per_chunk*2u-1u; j != j_max; ++j){
dmbr.do_allocate(s, 1);
}
//One due to the pool array, and for each pool, log2(max_blocks_per_chunk)+1 allocations
expected_memory_allocs = 1 + (bid::floor_log2(opts.max_blocks_per_chunk) + 1u)*(i+1);
//pool array plus each previous chunk allocation
BOOST_TEST(mrl.m_info.size() == expected_memory_allocs);
}
//Now with out-of-pool sizes
for(std::size_t j = 0, j_max = opts.max_blocks_per_chunk*2u-1u; j != j_max; ++j){
dmbr.do_allocate(maximum_size+1, 1);
BOOST_TEST(mrl.m_info.size() == ++expected_memory_allocs);
}
//Don't release, all memory, including internal allocations, should be automatically
//after the destructor is run
}
BOOST_TEST(mrl.m_mismatches == 0u);
BOOST_TEST(mrl.m_info.size() == 0u);
}
template<class PoolResource>
void test_pool_resource()
{
test_options_upstream_constructor<PoolResource>();
test_default_constructor<PoolResource>();
test_upstream_constructor<PoolResource>();
test_options_constructor<PoolResource>();
test_options<PoolResource>();
test_do_allocate_deallocate<PoolResource>();
test_do_is_equal<PoolResource>();
test_release<PoolResource>();
test_destructor<PoolResource>();
}
| {
"content_hash": "560ce50808b21cb4df456b9e79c19fa9",
"timestamp": "",
"source": "github",
"line_count": 484,
"max_line_length": 126,
"avg_line_length": 42.61776859504132,
"alnum_prop": 0.6271876666505066,
"repo_name": "zjutjsj1004/third",
"id": "72d8abf641aa42c57539665bace40422f3b7a406",
"size": "21060",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "boost/libs/container/test/pool_resource_test.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "224158"
},
{
"name": "Batchfile",
"bytes": "33175"
},
{
"name": "C",
"bytes": "5576593"
},
{
"name": "C#",
"bytes": "41850"
},
{
"name": "C++",
"bytes": "179595990"
},
{
"name": "CMake",
"bytes": "28348"
},
{
"name": "CSS",
"bytes": "331303"
},
{
"name": "Cuda",
"bytes": "26521"
},
{
"name": "FORTRAN",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "1305458"
},
{
"name": "HTML",
"bytes": "159660377"
},
{
"name": "IDL",
"bytes": "15"
},
{
"name": "JavaScript",
"bytes": "285786"
},
{
"name": "Lex",
"bytes": "1290"
},
{
"name": "Makefile",
"bytes": "1202020"
},
{
"name": "Max",
"bytes": "37424"
},
{
"name": "Objective-C",
"bytes": "3674"
},
{
"name": "Objective-C++",
"bytes": "651"
},
{
"name": "PHP",
"bytes": "60249"
},
{
"name": "Perl",
"bytes": "37297"
},
{
"name": "Perl6",
"bytes": "2130"
},
{
"name": "Python",
"bytes": "1833677"
},
{
"name": "QML",
"bytes": "613"
},
{
"name": "QMake",
"bytes": "17385"
},
{
"name": "Rebol",
"bytes": "372"
},
{
"name": "Shell",
"bytes": "1144162"
},
{
"name": "Tcl",
"bytes": "1205"
},
{
"name": "TeX",
"bytes": "38313"
},
{
"name": "XSLT",
"bytes": "564356"
},
{
"name": "Yacc",
"bytes": "20341"
}
],
"symlink_target": ""
} |
var Value = require('basis.data').Value;
var Node = require('basis.ui').Node;
var createEvent = require('basis.event').create;
var template = require('basis.template');
var templates = template.define('app.ui', {
page: resource('./template/page.tmpl')
});
module.exports = Node.subclass({
template: templates.page,
emit_open: createEvent('open'),
emit_close: createEvent('close'),
binding: {
content: 'satellite:',
type: 'type'
},
handler: basis.Class.extensibleProperty({
ownerChanged: function() {
if (this.owner) {
this.emit_open();
this.opened.set(true);
} else {
this.emit_close();
this.opened.set(false);
}
}
}),
init: function() {
this.opened = new Value({ value: !!this.owner });
Node.prototype.init.call(this)
},
destroy: function() {
this.destroy();
this.opened = null;
Node.prototype.destroy.call(this)
}
});
| {
"content_hash": "230924126151916ae04de0e17ed0daaf",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 57,
"avg_line_length": 27.42105263157895,
"alnum_prop": 0.5499040307101728,
"repo_name": "smelukov/webpack-runtime-analyzer",
"id": "a924b87457e00371323426ceae1230e33800579b",
"size": "1042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ui/src/ui/page/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12981"
},
{
"name": "HTML",
"bytes": "790"
},
{
"name": "JavaScript",
"bytes": "123173"
}
],
"symlink_target": ""
} |
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="binding-test-container">
<template>
<!-- <binding-test child-message="[[ issa ]]"></binding-test> -->
<binding-test child-message="{{ issa }}"></binding-test>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'binding-test-container',
properties: {
issa: {
type: String,
value : "PARENT",
notify: true
}
}
});
})();
</script>
</dom-module>
| {
"content_hash": "630f904b72220a628bcb0fbd71829c51",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 100,
"avg_line_length": 27.789473684210527,
"alnum_prop": 0.6524621212121212,
"repo_name": "ifaris7/polymer-playground",
"id": "a9cdae1109d347504e3a14d0dd95638d2f700240",
"size": "1056",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/elements/binding-test-container/binding-test-container.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "823"
},
{
"name": "HTML",
"bytes": "79156"
},
{
"name": "JavaScript",
"bytes": "14112"
}
],
"symlink_target": ""
} |
class NotificationParam < ActiveRecord::Base
belongs_to :notification, :inverse_of => :params, :touch => true
belongs_to :query_param
delegate :name, :value_type, :type, :default_value, to: :query_param
validate do
if self.query_param.query.id != self.notification.query.id
self.errors.add :value, :mismatch_query
end
# Copied from QueryParam, extract to module or concern
unless value.to_s.empty?
case value_type
when QueryParam::VALUE_DATE
begin
unless value.is_a?(ActiveSupport::TimeWithZone)
Date.parse(value)
end
rescue ArgumentError
self.errors.add :default_value, :invalid_date
end
value
when QueryParam::VALUE_DATETIME
begin
DateTime.parse(value)
rescue ArgumentError
self.errors.add :default_value, :invalid_date_time
end
value
when QueryParam::VALUE_TIME
begin
Time.parse(value)
rescue ArgumentError
self.errors.add :default_value, :invalid_time
end
when QueryParam::VALUE_INTEGER
if value.to_i.to_s != value.to_s
self.errors.add :default_value, :invalid_integer
end
when QueryParam::VALUE_FLOAT
if value.to_f.to_s != value.to_s
self.errors.add :default_value, :invalid_float
end
end
end
end
def parsed_value
self.query_param.parsed_value
end
end
| {
"content_hash": "bcb9d96fa93aa055b675673ed5a96eca",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 70,
"avg_line_length": 27.375,
"alnum_prop": 0.5929549902152642,
"repo_name": "tiagoamaro/sapos",
"id": "0de5a06a85b1614305d769ff239dc258ac495066",
"size": "1674",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/notification_param.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37632"
},
{
"name": "CoffeeScript",
"bytes": "229"
},
{
"name": "HTML",
"bytes": "58002"
},
{
"name": "JavaScript",
"bytes": "53664"
},
{
"name": "Ruby",
"bytes": "1427477"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.