A rollup function for d3.dest(), that aggregates the plot property value and
returns objects in the form <code>{ date : Date(..), y : Number, plus : Number, minus : Number }</code>.
775202
function nestRollupAggregateSum(array) {
		// Note: we don't use d3.sum here because we want to end up with a null value for "holes"
		var sum = null, plus = null, minus = null, 
			d, v, i, len = array.length, groupId, scale, negate = false;
		for ( i = 0; i < len; i += 1 ) {
			d = array[i];
			v = d[parent.plotPropertyName];
			if ( v !== undefined ) {
				groupId = d[parent.internalPropName].groupId;
				scale = parent.scaleFactor(groupId);
				negate = negativeGroupMap[groupId] === true;
				if ( negate ) {
					minus += v * scale;
				} else {
					plus += v * scale;
				}
			}
		}
		if ( plus !== null || minus !== null ) {
			sum = plus - minus;
		}
		return { date : array[0].date, y : sum, plus : plus, minus : minus };
	}
1243433
function id(d) {

    if (!d.d3plus.id) {
      d.d3plus.id = "";
      for (var i = 0; i <= vars.depth.value; i++) {
        d.d3plus.id += fetchValue(vars,d,vars.id.nesting[i])+"_"
      }

      d.d3plus.id += shape;

      ["x", "y", "x2", "y2"].forEach(function(axis){
        if (vars[axis].scale.value == "discrete") {
          var val = fetchValue(vars, d, vars[axis].value)
          if (val.constructor === Date) val = val.getTime()
          d.d3plus.id += "_"+val
        }
      })

      if (d.d3plus.suffix) {
        d.d3plus.id += "_" + d.d3plus.suffix;
      }

      d.d3plus.id = stringStrip(d.d3plus.id)
    }

    return d
  }
549428
function getDataByDate(data) {
            return d3Collection.nest()
                .key(getDate)
                .entries(
                    data.sort((a, b) => a.date - b.date)
                )
                .map(d => {
                    return assign({}, d, {
                        date: new Date(d.key)
                    });
                });

            // let b =  d3Collection.nest()
            //                     .key(getDate).sortKeys(d3Array.ascending)
            //                     .entries(data);
        }
504476
function TimeseriesHistogram( canvas, width, height, left, top ) {
		var graph, data, histogram, edges, axes, annotations, title, text, means;

		// [1] Instantiate a new graph generator and configure:
		graph = xfig.graph( canvas )
			.width( width )
			.height( height )
			.position({
				'left': left,
				'top': top
			})
			.xMin( 0 )
			.xMax( 1 );

		// Create the graph:
		graph.create( 'timeseries-histogram' );

		// Get data:
		d3.json( 'data/timeseries-histogram.data.json', function ( error, json ) {

			// [2] Instantiate a new data generator and configure:
			data = xfig.data( json )
				.accessors( 'x', function ( d ) {
					return d[ 0 ];
				})
				.accessors( 'y', function ( d ) {
					return d[ 1 ];
				});

			// Create edges to define our histogram bins:
			edges = xfig.vector.linspace( -0.025, 1.025, 0.05 );
			
			// Format the data and extract the data to histogram:
			data.format( [ 'x', 'y' ] )
				.extract( function ( d ) {
					return d[ 1 ];
				});

			// Calculate each dataset's mean value and sort the datasets based on their means:
			means = data.mean( function ( d ) {
				return d;
			});
			means = means.map( function ( d, i ) {
				return [ d, i ];
			});
			means.sort( function ( a, b ) {
				return a[0] < b[0] ? -1 : ( a[0] > b[0] ? 1 : 0 );
			});
			means = means.map( function ( d ) {
				return d[ 1 ];
			});

			// Calculate the histogram:
			data.reorder( means )
				.histc( function ( d ) { return d; }, edges );

			// Bind the data instance to the graph:
			graph.data( data )
				.yMin( 0 )
				.yMax( data.size()[0] )
				.zMin( 0 )
				.zMax( data.max( function ( d ) {
					return d[ 1 ];
				}))
				.zRange( ['#ffffff', '#000000'] );

			// [3] Instantiate a new histogram generator and configure:
			histogram = xfig.timeserieshistogram( graph );

			// Create the histogram:
			histogram.create();

			// [4] Instantiate a new axes generator and configure:
			axes = xfig.axes( graph )
				.xLabel( 'percent' )
				.yLabel( 'index' );

			// Create the axes:
			axes.create();

			// [5] Instantiate a new annotations generator and configure:
			annotations = xfig.annotations( graph );

			// Create the annotations element:
			annotations.create();

			// [5.1] Instantiate a new title instance and configure:
			title = annotations.title()
				.top( -30 )
				.left( 0 );

			// Add a (sub)title:
			title.create( 'Subtitle' );

		});

	}
368161
private Double aggregate(Datasource ds, Collection<Double> values) {
        return ((values.size() / m_intervalsPer) > ds.getXff()) ? ds.getAggregationFuction().apply(values) : Double.NaN;
    }
302893
function (d, chart, series) {
            var returnWidth = 0;
            if (series.x.measure !== null && series.x.measure !== undefined) {
                returnWidth = Math.abs(series.x._scale((d.x < 0 ? d.x - d.width : d.x + d.width)) - series.x._scale(d.x));
            } else if (series.x._hasTimeField()) {
                returnWidth = series.x.floatingBarWidth;
            } else {
                returnWidth = d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) - (dimple._helpers.xClusterGap(d, chart, series) * 2);
            }
            return returnWidth;
        }
840894
function (d, chart, series) {
            var returnY = 0;
            if (series.y._hasTimeField()) {
                returnY = series.y._scale(d.y) - (dimple._helpers.height(d, chart, series) / 2);
            } else if (series.y.measure !== null && series.y.measure !== undefined) {
                returnY = series.y._scale(d.y);
            } else {
                returnY = (series.y._scale(d.y) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + (d.yOffset * (dimple._helpers.height(d, chart, series) + 2 * dimple._helpers.yClusterGap(d, chart, series))) + dimple._helpers.yClusterGap(d, chart, series);
            }
            return returnY;
        }
1258697
function(d, range){
		"use strict";

		var start = new Date(d.getFullYear(), 0);
		var stop = null;
		if (range instanceof Date) {
			stop = new Date(range.getFullYear(), 0);
		} else {
			stop = new Date(d.getFullYear()+range, 0);
		}

		return d3.time.years(Math.min(start, stop), Math.max(start, stop));
	}
1011952
def plot_ts(fignum, dates, ts):
    
    vertical_plot_init(fignum, 10, 3)
    TS, Chrons = pmag.get_ts(ts)
    p = 1
    X, Y = [], []
    for d in TS:
        if d <= dates[1]:
            if d >= dates[0]:
                if len(X) == 0:
                    ind = TS.index(d)
                    X.append(TS[ind - 1])
                    Y.append(p % 2)
                X.append(d)
                Y.append(p % 2)
                p += 1
                X.append(d)
                Y.append(p % 2)
        else:
            X.append(dates[1])
            Y.append(p % 2)
            plt.plot(X, Y, 'k')
            plot_vs(fignum, dates, 'w', '-')
            plot_hs(fignum, [1.1, -.1], 'w', '-')
            plt.xlabel("Age (Ma): " + ts)
            isign = -1
            for c in Chrons:
                off = -.1
                isign = -1 * isign
                if isign > 0:
                    off = 1.05
                if c[1] >= X[0] and c[1] < X[-1]:
                    plt.text(c[1] - .2, off, c[0])
            return
660801
def object_deserializer(obj):
    
    for key, val in obj.items():
        if isinstance(val, six.string_types) and DATETIME_REGEX.search(val):
            try:
                obj[key] = dates.localize_datetime(parser.parse(val))
            except ValueError:
                obj[key] = val
    return obj
216693
def D(self, ID, asp):
        
        obj = self.chart.getObject(ID).copy()
        obj.relocate(obj.lon - asp)
        ID = 'D_%s_%s' % (ID, asp)
        return self.G(ID, obj.lat, obj.lon)
623139
function convertDates (obj, convert) {
  obj = clone(obj);
  for (var key in obj) {
    var val = obj[key];
    if (is.date(val)) obj[key] = convert(val);
    if (is.object(val)) obj[key] = convertDates(val, convert);
  }
  return obj;
}
301656
function filterDate({
  data,
  value,
  disabledArr,
  minDate,
  maxDate,
  oldData = {},
  props,
  columns,
}) {
  const disabledArrNew = parseDisabledArr(disabledArr);
  if (columns[0] === 'Y') {
    const year = value[0].value;
    let month;
    let yearData = data[0];
    let monthData;
    if (columns.length >= 2) {
      monthData = getMonthsByYear({ year, minDate, maxDate }).map(item => ({
        value: item.value,
        text: `${addZero(item.text)}${locale[props.locale].surfix.M}`,
      }));
      month = value[1].value;
    }
    let dayData;
    if (columns.length >= 3) {
      dayData = getDaysByMonth({
        year, month, minDate, maxDate,
      });
    }
    if (disabledArrNew.startEnd || disabledArrNew.minTime || disabledArrNew.maxTime) {
      if (oldData.yearData) {
        ({ yearData } = oldData);
      } else {
        yearData = filterYear(yearData, { disabledDateObj: disabledArrNew, minDate, maxDate });
      }
      if (monthData) {
        if (oldData.monthData) {
          ({ monthData } = oldData);
        } else {
          const monthArr = filterMonth(monthData, year, disabledArrNew);
          monthData = monthArr.length ? monthArr : monthData;
        }
      }

      if (dayData) {
        const dayArr = filterDay(dayData, year, month, disabledArrNew);
        dayData = dayArr.length ? dayArr : dayData;
        const unit = locale[props.locale].surfix.D;
        dayData = dayData.map(item => ({
          ...item,
          text: addZero(item.text) + (unit || ''),
        }));
      }
    }
    if (disabledArrNew.minTime >= disabledArrNew.maxTime) {
      warn('Datetime: Please check your disabledDate props');
      return [];
    }
    if (!yearData.length) {
      return [];
    }
    const outArr = [yearData];
    if (monthData) {
      outArr.push(monthData);
      if (dayData) {
        outArr.push(dayData);
      }
    }

    if (data[3]) {
      outArr.push(data[3]);
    }
    return outArr;
  }
  if (['YMD', 'YMDW'].indexOf(columns[0]) !== -1) {
    const newData = [...data];
    newData[0] = filterYMDDay(newData[0], disabledArr);

    return newData;
  }
  return data;
}
1238071
function (dst) {
    forEach(arguments, function (obj) {
        if (obj !== dst) {
            forEach(obj, function (value, key) {
                if (instanceKeywords.indexOf(key) === -1) {
                    if (dst[key]) {
                        if (angular.isArray(dst[key])) {
                            dst[key].concat(value.filter(function (v) {
                                var vv = dst[key].indexOf(v) !== -1;
                                if (vv) extendDeep(vv, v);
                                return vv;
                            }));
                        } else if (angular.isObject(dst[key])) {
                            extendDeep(dst[key], value);
                        } else {
                            // if value is a simple type like a string, boolean or number
                            // then assign it
                            dst[key] = value;
                        }
                    } else if (!angular.isFunction(dst[key])) {
                        dst[key] = value;
                    }
                }
            });
        }
    });
    return dst;
}
352737
function(d) {
    return d.dcEnd || (d.dcEnd =
      later.date.prev(
        later.Y.val(d),
        later.M.val(d),
        Math.min(later.dc.val(d) * 7, later.D.extent(d)[1])));
  }
534214
def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True,
                         coerce=False, copy=True):
    

    conversion_count = sum((datetime, numeric, timedelta))
    if conversion_count == 0:
        raise ValueError('At least one of datetime, numeric or timedelta must '
                         'be True.')
    elif conversion_count > 1 and coerce:
        raise ValueError("Only one of 'datetime', 'numeric' or "
                         "'timedelta' can be True when when coerce=True.")

    if isinstance(values, (list, tuple)):
        # List or scalar
        values = np.array(values, dtype=np.object_)
    elif not hasattr(values, 'dtype'):
        values = np.array([values], dtype=np.object_)
    elif not is_object_dtype(values.dtype):
        # If not object, do not attempt conversion
        values = values.copy() if copy else values
        return values

    # If 1 flag is coerce, ensure 2 others are False
    if coerce:
        # Immediate return if coerce
        if datetime:
            from pandas import to_datetime
            return to_datetime(values, errors='coerce').to_numpy()
        elif timedelta:
            from pandas import to_timedelta
            return to_timedelta(values, errors='coerce').to_numpy()
        elif numeric:
            from pandas import to_numeric
            return to_numeric(values, errors='coerce')

    # Soft conversions
    if datetime:
        # GH 20380, when datetime is beyond year 2262, hence outside
        # bound of nanosecond-resolution 64-bit integers.
        try:
            values = lib.maybe_convert_objects(values,
                                               convert_datetime=datetime)
        except OutOfBoundsDatetime:
            pass

    if timedelta and is_object_dtype(values.dtype):
        # Object check to ensure only run if previous did not convert
        values = lib.maybe_convert_objects(values, convert_timedelta=timedelta)

    if numeric and is_object_dtype(values.dtype):
        try:
            converted = lib.maybe_convert_numeric(values, set(),
                                                  coerce_numeric=True)
            # If all NaNs, then do not-alter
            values = converted if not isna(converted).all() else values
            values = values.copy() if copy else values
        except Exception:
            pass

    return values
1062585
def df2arff(df, dataset_name, pods_data):
    """"""
    def java_simple_date(date_format):
        date_format = date_format.replace('%Y', 'yyyy').replace('%m', 'MM').replace('%d', 'dd').replace('%H', 'HH')
        return date_format.replace('%h', 'hh').replace('%M', 'mm').replace('%S', 'ss').replace('%f', 'SSSSSS')
    
    def tidy_field(atr):
        return str(atr).replace(' / ', '/').replace(' ', '_')
    types = {'STRING': [str], 'INTEGER': [int, np.int64, np.uint8], 'REAL': [np.float64]}
    d = {}
    d['attributes'] = []
    for atr in df.columns:
        if isinstance(atr, str):
            if len(atr)>8 and atr[:9] == 'discrete(':
                import json
                elements = json.loads(atr[9:-1])
                d['attributes'].append((tidy_field(elements[1]),
                                         list(elements[0].keys())))
                mask = {}
                c = pd.Series(index=df.index)
                for key, val in elements[0].items():
                    mask = df[atr]==val
                    c[mask] = key
                df[atr] = c
                continue
            if len(atr)>7 and atr[:8] == 'integer(':
                name = atr[8:-1]
                d['attributes'].append((tidy_field(name), 'INTEGER'))
                df[atr] = df[atr].astype(int)
                continue
            if len(atr)>7 and atr[:8]=='datenum(':
                from matplotlib.dates import num2date
                elements = atr[8:-1].split(',')
                d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING'))
                df[atr] = num2date(df[atr].values) #
                df[atr] = df[atr].dt.strftime(elements[1])
                continue
            if len(atr)>9 and atr[:10]=='timestamp(':
                def timestamp2date(values):
                    import datetime
                    """Convert timestamp into a date object"""
                    new = []
                    for value in values:
                        new.append(np.datetime64(datetime.datetime.fromtimestamp(value)))
                    return np.asarray(new)
                elements = atr[10:-1].split(',')
                d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING'))
                df[atr] = timestamp2date(df[atr].values) #
                df[atr] = df[atr].dt.strftime(elements[1])
                continue
            if len(atr)>10 and atr[:11]=='datetime64(':
                elements = atr[11:-1].split(',')
                d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING'))
                df[atr] = df[atr].dt.strftime(elements[1])
                continue
            if len(atr)>11 and atr[:12]=='decimalyear(':
                def decyear2date(values):
                    """Convert decimal year into a date object"""
                    new = []
                    for i, decyear in enumerate(values):
                        year = int(np.floor(decyear))
                        dec = decyear-year
                        end = np.datetime64(str(year+1)+'-01-01')
                        start = np.datetime64(str(year)+'-01-01')
                        diff=end-start
                        days = dec*(diff/np.timedelta64(1, 'D'))
                        # round to nearest day
                        add = np.timedelta64(int(np.round(days)), 'D')
                        new.append(start+add)
                    return np.asarray(new)
                elements = atr[12:-1].split(',')
                d['attributes'].append((elements[0] + '_datenum_' + java_simple_date(elements[1]), 'STRING'))
                df[atr] = decyear2date(df[atr].values) #
                df[atr] = df[atr].dt.strftime(elements[1])
                continue

        field = tidy_field(atr)
        el = df[atr][0]
        type_assigned=False
        for t in types:
            if isinstance(el, tuple(types[t])):
                d['attributes'].append((field, t))
                type_assigned=True
                break
        if not type_assigned:
            import json
            d['attributes'].append((field+'_json', 'STRING'))
            df[atr] = df[atr].apply(json.dumps)

    d['data'] = []
    for ind, row in df.iterrows():
        d['data'].append(list(row))

    import textwrap as tw
    width = 78
    d['description'] = dataset_name + "\n\n"
    if 'info' in pods_data and pods_data['info']:
        d['description'] += "\n".join(tw.wrap(pods_data['info'], width)) + "\n\n"
    if 'details' in pods_data and pods_data['details']:
        d['description'] += "\n".join(tw.wrap(pods_data['details'], width))
    if 'citation' in pods_data and pods_data['citation']:
        d['description'] += "\n\n" + "Citation" "\n\n" + "\n".join(tw.wrap(pods_data['citation'], width))

    d['relation'] = dataset_name
    import arff
    string = arff.dumps(d)
    import re
    string = re.sub(r'\@ATTRIBUTE "?(.*)_datenum_(.*)"? STRING',
                    r'@ATTRIBUTE "\1" DATE [\2]',
                    string)
    f = open(dataset_name + '.arff', 'w')
    f.write(string)
    f.close()