#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 08:52:52 2020

@author: ictd
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 11:44:26 2020

@author: ictd
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 10:47:44 2020

@author: ictd
"""

import pandas as pd
import numpy as np
from loadSeries import *
from datetime import timedelta
from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
import sklearn
#np.random.seed(42)

n_estimators = [int(x) for x in np.linspace(start = 2, stop = 10, num = 5)]
max_features = ['auto', 'sqrt']
max_depth = [int(x) for x in np.linspace(2, 8, num =4)]
max_depth.append(None)
min_samples_split = [int(x) for x in range(2,4)]
min_samples_leaf = [int(x) for x in range(2,4)]
bootstrap = [True,False]
#oob_score=[True,False]
random_grid = {'n_estimators': n_estimators,
               'max_features': max_features,
               'max_depth': max_depth,
               'min_samples_split': min_samples_split,
               'min_samples_leaf': min_samples_leaf,
               'bootstrap': bootstrap}
rf = RandomForestClassifier()

#kolkata_mandi_arimax2.index=pd.to_datetime(kolkata_mandi_arimax2[0])
#kolkata_mandi_arimax2=kolkata_mandi_arimax2[1]
#
#bangalore_mandi_arimax2.index=pd.to_datetime(bangalore_mandi_arimax2[0])
#bangalore_mandi_arimax2=bangalore_mandi_arimax2[1]
#
#lucknow_mandi_arimax2.index=pd.to_datetime(lucknow_mandi_arimax2[0])
#lucknow_mandi_arimax2=lucknow_mandi_arimax2[1]
#
#kolkata_arrival_arimax2.index=pd.to_datetime(kolkata_arrival_arimax2[0])
#kolkata_arrival_arimax2=kolkata_arrival_arimax2[1]
#
#bangalore_arrival_arimax2.index=pd.to_datetime(bangalore_arrival_arimax2[0])
#bangalore_arrival_arimax2=bangalore_arrival_arimax2[1]
#
#lucknow_arrival_arimax2.index=pd.to_datetime(lucknow_arrival_arimax2[0])
#lucknow_arrival_arimax2=lucknow_arrival_arimax2[1]

#delhi_retail_arimax2.index=pd.to_datetime(delhi_retail_arimax2[0])
#delhi_retail_arimax2=delhi_retail_arimax2[1]
#
#bangalore_retail_arimax2.index=pd.to_datetime(bangalore_retail_arimax2[0])
#bangalore_retail_arimax2=bangalore_retail_arimax2[1]
#
#mumbai_retail_arimax2.index=pd.to_datetime(mumbai_retail_arimax2[0])
#mumbai_retail_arimax2=mumbai_retail_arimax2[1]

def Normalise(arr):
  '''
  Normalise each sample
  '''
  m = arr.mean()
  am = arr.min()
  aM = arr.max()
  arr -= m
  arr /= (aM - am)
  return arr

kalyani_mandi=Normalise(kalyani_mandi)
lucknow_mandi=Normalise(lucknow_mandi)
bangalore_mandi=Normalise(bangalore_mandi)

kalyani_arrival=Normalise(kalyani_arrival)
bangalore_arrival=Normalise(bangalore_arrival)
lucknow_arrival=Normalise(lucknow_arrival)

delhi_retail=Normalise(delhi_retail)
bangalore_retail=Normalise(bangalore_retail)
mumbai_retail=Normalise(mumbai_retail)

kalyani_mandi_arimax2=Normalise(kalyani_mandi_arimax2)
lucknow_mandi_arimax2=Normalise(lucknow_mandi_arimax2)
bangalore_mandi_arimax2=Normalise(bangalore_mandi_arimax2)

kalyani_arrival_arimax2=Normalise(kalyani_arrival_arimax2)
bangalore_arrival_arimax2=Normalise(bangalore_arrival_arimax2)
lucknow_arrival_arimax2=Normalise(lucknow_arrival_arimax2)

delhi_retail_arimax2=Normalise(delhi_retail_arimax2)
bangalore_retail_arimax2=Normalise(bangalore_retail_arimax2)
mumbai_retail_arimax2=Normalise(mumbai_retail_arimax2)

def newlabels(df):
#    df.loc[df[2]!='HOARDING',2]=1
#    df.loc[df[2]=='HOARDING',2]=0
    ##print(df)
    ##print(df)
    for i in range(len(df)):
        if(df.iloc[i][2]=='hoarding'):
            df.iloc[i][2]=1
        else:
            df.iloc[i][2]=0
    return df

def process_train_data(anomalies,start_date):
    anomalies=anomalies[anomalies[1]<=start_date]
    return anomalies

def process_test_data(anomalies,start_date,last_date):
    anomalies=anomalies[anomalies[1]>=start_date]
    anomalies=anomalies[anomalies[1]<=last_date]
    return anomalies

def prepare(anomalies,priceserieslist,days):
    x = []
    y=[]
    anomalies.reset_index(inplace=True)
    for i in range(0,len(anomalies)):
        ##print(i)
        p=[]
        ##print(datetime.strptime(anomalies[0][i], '%Y-%m-%d'))
        mid_date=datetime.strptime(anomalies[0][i], '%Y-%m-%d')+timedelta(21)
        start_date=mid_date-timedelta(int(days/2))
        end_date=mid_date+timedelta(int(days/2))
        ##print(start_date,end_date)
        for j in range(len(priceserieslist)):
            ##print(i,j)
            #priceserieslist[j]=pd.Series(priceserieslist[j])
            ##print(type(priceserieslist[j]))
            p+=(np.array(priceserieslist[j][start_date:end_date])).tolist()
        x.append(np.array(p))
        y.append(anomalies[2][i])
    return np.array(x),np.array(y)

def prepare_train_data(kolkata_low_anomaly,kolkata_mandi,lucknow_low_anomaly,
                       lucknow_mandi,days):
    #print('x1')
    x1,y1=prepare(kolkata_low_anomaly,kolkata_mandi,days)

    #print('x2')
    x2,y2=prepare(lucknow_low_anomaly,lucknow_mandi,days)

    #print('x3')
    #x3,y3=prepare(bangalore_low_anomaly,bangalore_mandi,days)

    #print(x1.shape,x2.shape)
#    x_all=np.concatenate((x1,x2),axis=0)
#    y_all=np.concatenate((y1,y2),axis=0)
#    return x_all,y_all

    l_c=[0,0]
    l_x=[x1,x2]
    l_y=[y1,y2]
#    print(x1.shape,x2.shape,x3.shape)
    for i in range(len(l_c)):
        if(len(l_x[i])>0):
            l_c[i]=1
#    print(l_c)
    i=0
    while(i<len(l_c)):
        if(l_c[i]==1):
            x_all=l_x[i]
            y_all=l_y[i]
            i+=1
            break
    while(i<len(l_c)):
        if(l_c[i]==1):
            x_all=np.concatenate((x_all,l_x[i]),axis=0)
            y_all=np.concatenate((y_all,l_y[i]),axis=0)
        i+=1
#    x_all=np.concatenate((x1,x2),axis=0)
#    y_all=np.concatenate((y1,y2),axis=0)
    return x_all,y_all

def train_model(x_train,y_train):
#    #print('train model')
    ##print(y_train)
    n_estimators = [int(x) for x in np.linspace(start = 5, stop = 100, num = 20)]
    max_features = ['auto', 'sqrt']
    max_depth = [int(x) for x in np.linspace(2, 50, num =10)]
    max_depth.append(None)
    min_samples_split = [int(x) for x in range(2,10)]
    min_samples_leaf = [int(x) for x in range(2,10)]
    bootstrap = [True,False]
    #oob_score=[True,False]
    random_grid = {'n_estimators': n_estimators,
                   'max_features': max_features,
                   'max_depth': max_depth,
                   'min_samples_split': min_samples_split,
                   'min_samples_leaf': min_samples_leaf,
                   'bootstrap': bootstrap}
#    rf = RandomForestClassifier()
    model = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 10, cv = 3, iid=True,verbose=0,n_jobs=-1)# Fit the random search model
#    model = RandomForestClassifier(max_depth=3, random_state=0,n_estimators=20)
    model.fit(x_train, y_train)
    return model

def train_test_function(days,start_date,last_date,train_series1,train_series2,
                        test_series1,test_series2,anomaly1,anomaly2):

#    #print(train_series1[0][-30:])
#    #print(test_series1[0][-30:])

    #print('Processing train data:')
    train_anomaly1=process_train_data(anomaly1,start_date)
    train_anomaly2=process_train_data(anomaly2,start_date)
    #train_anomaly3=process_train_data(anomaly3,start_date)

    #print('processing test data:')
    test_anomaly1=process_test_data(anomaly1,start_date,last_date)
    test_anomaly1.index=np.arange(0, len(test_anomaly1))
    test_anomaly2=process_test_data(anomaly2,start_date,last_date)
    test_anomaly2.index=np.arange(0, len(test_anomaly2))
#    test_anomaly3=process_test_data(anomaly3,start_date,last_date)
#    test_anomaly3.index=np.arange(0, len(test_anomaly3))

    #print('Prepare train data for random forest')
    x_train,y_train=prepare_train_data(train_anomaly1,train_series1,
       train_anomaly2,train_series2,days)

    #print('Prepare test data for random forest')
    x_test,y_test=prepare_train_data(test_anomaly1,test_series1,
       test_anomaly2,test_series2,days)

    #print('Running model')
    model=train_model(x_train,y_train)
    #print(x_test.shape)
    pred=model.predict(x_test)
    return y_test,pred

def final_model(days,lucknow_mandi,kalyani_mandi,
                lucknow_mandi_arimax2,kalyani_mandi_arimax2,
                lucknow_low_anomaly,kolkata_low_anomaly):
    #print('new labels as 1/0:')
    ##print(str(anomaly1[2][0]))

    lucknow_low_anomaly=lucknow_low_anomaly[(lucknow_low_anomaly[2]=='hoarding') | (lucknow_low_anomaly[2]=='weather')]
    kolkata_low_anomaly=kolkata_low_anomaly[(kolkata_low_anomaly[2]=='hoarding') | (kolkata_low_anomaly[2]=='weather')]

    lucknow_low_anomaly=newlabels(lucknow_low_anomaly)
    kolkata_low_anomaly=newlabels(kolkata_low_anomaly)
    #lucknow_low_anomaly=newlabels(lucknow_low_anomaly)
#    #print(kolkata_low_anomaly)
#    #print(bangalore_low_anomaly)
#    #print(lucknow_low_anomaly)
    dates=['2011-01-01','2012-01-01','2013-01-01','2014-01-01','2015-01-01','2016-01-01','2017-01-01','2018-01-01','2019-01-01']
    predcited_labels=[]
    actual_labels=[]
    for i in range(len(dates)-1):
        #print(dates[i],dates[i+1])
        start_date=dates[i]
        last_date=dates[i+1]
        #print(start_date)
        #print(last_date)
        act,pred=train_test_function(days,start_date,last_date,lucknow_mandi,kalyani_mandi,
                        lucknow_mandi_arimax2,kalyani_mandi_arimax2,
                        lucknow_low_anomaly,kolkata_low_anomaly)
        ##print(act)
        ##print(pred)
        predcited_labels.extend(pred)
        actual_labels.extend(act)
    return actual_labels,predcited_labels

##print(type(lucknow_arrival_arimax2))
##print(type(kalyani_arrival_arimax2))
##print(type(lucknow_arrival))
##print(type(kalyani_arrival))

#print(len(kolkata_high_anomaly))
#print(len(lucknow_high_anomaly))

days=29
#print('------------------------Mandi Price----------------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_mandi],[kalyani_mandi],
#                        [lucknow_mandi_arimax2],[kalyani_mandi_arimax2],
#                        lucknow_high_anomaly,kolkata_high_anomaly)

#print('------------------------Arrival----------------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_arrival],[kalyani_arrival],
#                        [lucknow_arrival_arimax2],[kalyani_arrival_arimax2],
#                        lucknow_high_anomaly,kolkata_high_anomaly)

#
#print('-------------------Arrival and Mandi----------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_arrival,lucknow_mandi],[kalyani_arrival,kalyani_mandi],
#                        [lucknow_arrival_arimax2,lucknow_mandi_arimax2],[kalyani_arrival_arimax2,kalyani_mandi_arimax2]
#                        ,lucknow_high_anomaly,kolkata_high_anomaly)
##
#
#print('----------------------Retail----------------------------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_retail],[kolkata_retail],
#                        [lucknow_retail_arimax2],[kolkata_retail_arimax2],
#                        lucknow_high_anomaly,kolkata_high_anomaly)

#
#print('----------------Mandi and Retail---------------------------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_retail,lucknow_mandi],[kolkata_retail,kalyani_mandi],
#                        [lucknow_retail_arimax2,lucknow_mandi_arimax2],[kolkata_retail_arimax2,kalyani_mandi_arimax2],
#                        lucknow_high_anomaly,kolkata_high_anomaly)

#print('----------------arrival and Retail---------------------------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_retail,lucknow_arrival],[kolkata_retail,kalyani_arrival],
#                        [lucknow_retail_arimax2,lucknow_arrival_arimax2],[kolkata_retail_arimax2,kalyani_arrival_arimax2],
#                        lucknow_high_anomaly,kolkata_high_anomaly)

#print('----------------arrival and Retail and mandi---------------------------------------------')
#actual_labels,predicted_labels=final_model(days,[lucknow_retail,lucknow_arrival,lucknow_mandi],[kolkata_retail,kalyani_arrival,kalyani_mandi],
#                        [lucknow_retail_arimax2,lucknow_arrival_arimax2,lucknow_mandi_arimax2],[kolkata_retail_arimax2,kalyani_arrival_arimax2,kalyani_mandi_arimax2],
#                        lucknow_high_anomaly,kolkata_high_anomaly)

#print(actual_labels)
#print(accuracy_score(actual_labels,predicted_labels))
#print('final results')
#print(actual_labels)
#print(predicted_labels)
#print('Accuracy:')
print(str(accuracy_score(actual_labels,predicted_labels))[:6],str(f1_score(actual_labels,predicted_labels,average='weighted'))[:6])
#print('f1-score:')
#print(f1_score(actual_labels,predicted_labels,average='weighted'))
#from sklearn.metrics import confusion_matrix as cm
#print(cm(actual_labels,predicted_labels))


"""
监听事件，比如 app 唤醒，杀死，退出到后台等等
"""

from time import sleep

from ios_device.servers.DTXSever import DTXServerRPC
from ios_device.servers.Instrument import InstrumentServer
from ios_device.util.dtxlib import get_auxiliary_text

def MobileNotifications(rpc: DTXServerRPC):
    def dropped_message(res):
        print("[DROP]", res.parsed, get_auxiliary_text(res.raw))
    rpc.register_unhandled_callback(dropped_message)

    rpc.call(
        "com.apple.instruments.server.services.mobilenotifications",
        'setApplicationStateNotificationsEnabled:', str(True))
    sleep(5)
    rpc.call(
        "com.apple.instruments.server.services.mobilenotifications",
        'setApplicationStateNotificationsEnabled:', str(False))
    print("aaaaa")
    sleep(10)
    rpc.stop()

if __name__ == '__main__':
    rpc = InstrumentServer().init()
    MobileNotifications(rpc)
    rpc.stop()


#!/usr/bin/env python
#
# Copyright 2019-2023 Lawrence Livermore National Security, LLC and other
# Variorum Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT

from ctypes import create_unicode_buffer, addressof, c_char_p

from pyVariorum import variorum

if __name__ == "__main__":
    v = variorum.variorum()
    print("\n=== Running Variorum JSON Get Node Power Domain Info:")
    jsonbuf = create_unicode_buffer(1000)
    bufptr = c_char_p(addressof(jsonbuf))
    v.variorum_get_node_power_domain_info_json(bufptr)
    print(bufptr.value.decode("utf-8"))


#!/usr/bin/env python3

""" Contact tracing beacon transmitter """

__copyright__ = """
    Copyright 2020 Diomidis Spinellis

    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.
"""
__license__ = "Apache 2.0"

import argparse
import bluetooth._bluetooth as bluez
from datetime import datetime
from dp3t.protocols.unlinkable_db import ContactTracer
from epidose.common import logging
import struct
import sys

OGF_LE_CTL = 0x08
OCF_LE_SET_SCAN_ENABLE = 0x000C

def set_receive(socket):
    """Setup to receive contact tracing packets."""
    # Enable scanning
    enable_scanning = struct.pack("<BB", 0x01, 0x00)
    bluez.hci_send_cmd(socket, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, enable_scanning)

    # Obtain Bluetooth advertisement packets
    socket.getsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, 14)
    listen_filter = bluez.hci_filter_new()
    bluez.hci_filter_all_events(listen_filter)
    bluez.hci_filter_set_ptype(listen_filter, bluez.HCI_EVENT_PKT)
    socket.setsockopt(bluez.SOL_HCI, bluez.HCI_FILTER, listen_filter)

def unpack_byte(b):
    """Return b unpacked from a byte value"""
    return struct.unpack("b", bytes([b]))

def process_packet(socket):
    """Read and process a single broadcast packet."""
    packet = socket.recv(255)

    # TODO: This is both too frequent (it triggers for every packet) and
    # can also be too infrequent (if no packets are received)
    now = datetime.now()
    receiver.check_advance_day(now)

    # Early exit for other packets
    (packet_length,) = unpack_byte(packet[2])
    if packet_length != 42:
        return
    if packet[17:18] != bytes([0x1B]):
        return
    # Ensure the packet is     AltBeacon,  cntct-trc,  v1,   app 1
    if packet[21:27] != bytes([0xBE, 0xAC, 0xED, 0x05, 0x01, 0x01]):
        return

    # This is a contact tracing packet
    ephid = packet[27:43]
    (rssi,) = unpack_byte(packet[-1])
    logger.info(f"Got ephid {ephid.hex()} RSSI {rssi}")

    receiver.add_observation(ephid, now, rssi)

def main():
    parser = argparse.ArgumentParser(description="Contact tracing beacon receiver")
    parser.add_argument(
        "-d", "--debug", help="Run in debug mode logging to stderr", action="store_true"
    )
    parser.add_argument(
        "-D",
        "--database",
        help="Specify the database location",
        default="/var/lib/epidose/client-database.db",
    )
    parser.add_argument(
        "-i",
        "--iface",
        help="Listen on the specified interface number, not [hci]0",
        type=int,
        default=0,
    )
    parser.add_argument("-t", "--test", help="Test script", action="store_true")
    parser.add_argument(
        "-v", "--verbose", help="Set verbose logging", action="store_true"
    )
    args = parser.parse_args()

    if args.test:
        args.debug = True
        args.database = ":memory:"

    # Setup logging
    global logger
    logger = logging.getLogger("beacon_rx", args)

    # Receive and process beacon packets
    global receiver
    receiver = ContactTracer(None, args.database, transmitter=False)
    if args.test:
        sys.exit(0)
    socket = bluez.hci_open_dev(args.iface)
    set_receive(socket)
    while True:
        process_packet(socket)

if __name__ == "__main__":
    main()


import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
import os
import glob

input_path = "/home/nemo/Audio/hat_jakub_raw/*.wav"
output_path = "/home/nemo/Audio/hat_jakub/"
print(glob.glob(input_path))

counter = 0;
for x in range(1):
    for i in glob.glob(input_path):
        fs, x = wavfile.read(i)
        if x.ndim ==2:
            x_clip = x[1100:17100, 1]
            print(x_clip.shape)
            print("2d fixed")
        else:
            x_clip = x[1100:17100]
            print(x_clip.shape)
        wavfile.write(output_path+'recording_j_'+str(counter)+'.wav', fs, x_clip)
        counter = counter+1
#files = os.listdir('*.wav')
#print(len(files))
fs, x = wavfile.read('/home/nemo/Audio/biscuit_jakub/recording_j_0.wav')
print(x.shape)
x = x[1100:17100, 1]
print(fs)
## ==> 16000
print(x.shape)
   ## ==> (16000,)
#plt.plot(x)
#plt.grid(True)


'''
Created on Mar 22, 2017

@author: nick
'''

from StringIO import StringIO
from datetime import datetime
from time import gmtime, mktime

import requests

from PH5WebService.common.log import ds_logger

class RestrictedRequest(object):
    """
    Container for the forbidden request information returned
    by the ws-restrited service
    """
    def __init__(self, network, station, location,
                 channel, starttime, endtime):
        self.network = network
        self.station = station
        self.location = location
        self.channel = channel
        self.starttime = starttime
        self.endtime = endtime

def get_epoch_seconds(date_to_convert):
    return (date_to_convert - datetime.fromtimestamp(mktime(gmtime(0)))) \
            .total_seconds()

def parse_restricted_date(restricted_date):
    """
    Convert ws-restricted date string to a python datetime object.
    @param restricted_date: A date string returned by the ws-restricted
        service.
    @type string
    @return float: date in seconds
    """
    if len(restricted_date.split(".")[-1]) > 6:
        # trim to microseconds
        restricted_date = restricted_date[:-3]
    try:
        return get_epoch_seconds(datetime.strptime(restricted_date,
                                                   "%Y-%m-%dT%H:%M:%S.%f"))
    except ValueError:
        try:
            return get_epoch_seconds(datetime.strptime(restricted_date,
                                                       "%Y,%j,%H,%M,%S.%f"))
        except ValueError as e:
            raise ValueError("Unable to parse restricted date: %s" % e)

def str_to_restricted_request(restricted_sncl_str):
    """
    Converts a SNCL string returned by the ws-restricted service into a
    RestrictedRequest object
    @param restricted_sncl_str: Network, Stations, Location and Channels
    returned by the ws-restricted web service
    @type string
    @return RestrictedRequest
    """
    items = restricted_sncl_str.strip().rsplit(" ")
    network = items[0]
    station = items[1]
    location = (items[2] if items[2] != "--" else "")
    channel = items[3]
    # skip quality flag - items[4]
    starttime = parse_restricted_date(items[5])
    endtime = parse_restricted_date(items[6])
    return RestrictedRequest(network, station, location,
                             channel, starttime, endtime)

def parse_response(response):
    """
    Parses the text response from the ws-restricted service and returns a
    list of restricted data objects
    @param response: The response from the ws-restricted service request
    @type string
    @return list<RestrictedRequest>
    """
    restricted_requests = []
    found_forbidden = False
    # create a list of all forbidden sncls and time ranges if any
    for line in response.iter_lines():
        if found_forbidden:
            r = str_to_restricted_request(line)
            restricted_requests.append(r)
        if line == "forbidden:":
            found_forbidden = True
    return restricted_requests

def get_request_body(avail_data_list, auth_username):
    """
    Creates the text body of a HTTP POST request to ws-restricted
    @param avail_data_list: List of available data objects
    @type list<AvailableData>
    @param auth_username: The username to use for authentication
    @type string
    @return string
    """
    request_body = StringIO()
    request_lines = []
    request_lines.append("user=%s" % auth_username)
    for r in avail_data_list:
        network = str(r.get_network())
        station = str(r.get_station()[0])
        location = str(r.get_location()[0])
        if location == "":
            location = "--"
        channel = str(r.get_channel()[0])
        starttime = r.get_starttime()
        endtime = r.get_endtime()
        req_line = "%s %s %s %s %s %s" % \
            (network,
             station,
             location,
             channel,
             starttime.strftime("%Y-%m-%dT%H:%M:%S"),
             endtime.strftime("%Y-%m-%dT%H:%M:%S"))
        request_lines.append(req_line)
    request_body.write("\n".join(request_lines))
    return request_body.getvalue()

def get_restricted_request_list(avail_data_list, auth_username):
    """
    Sends a request to the ws-restricted web service and returns a list of
    RestrictedData objects.
    @param avail_data_list: List of available data objects
    @type list<AvailableData>
    @param auth_username: The username to use for authentication
    @type string
    @return list<RestrictedRequest>
    """
    # POST to ws-restricted and read response
    request_body = get_request_body(avail_data_list, auth_username)
    url = "http://service-int/iriswsint/restricted/0/filter"
    response = requests.post(url, data=request_body)
    if response.status_code != 200:
        ds_logger.warning('HTTP POST to ws-restricted failed.')

    # create a restricted data object from the ws response
    return parse_response(response)