schedule and download a v13 report
6234
def schedule(argv)

      report = @account.report do
        name            'boh'
        type            'Url'
        aggregation     'Daily'
        cross_client    true
        zero_impression true

        start_day '2010-01-01'
        end_day   '2010-01-30'

        column "CustomerName"
        column "ExternalCustomerId"
        column "CampaignStatus"
        column "Campaign"
        column "CampaignId"
        column "AdGroup"
        column "AdGroupId"
        column "AdGroupStatus"
        column "QualityScore"
        column "FirstPageCpc"
        column "Keyword"
        column "KeywordId"
        column "KeywordTypeDisplay"
        column "DestinationURL"
        column "Impressions"
        column "Clicks"
        column "CTR"
        column "CPC"
        column "MaximumCPC"
        column "Cost"
        column "AveragePosition"
      end

      unless report.validate
        puts "report not valid"
        exit
      end
      puts "scheduled job"
      job = report.schedule
      job.wait(10) { |report, status| puts "status #{status}" }
      report.download("test_report.xml")
      true
    end
917742
def get_reports(self, **params):
        """"""
        response = self._get('v2', 'reports', data=params)
        return self._make_api_object(response, Report)
1036368
def get_schedule(self, date=None):
        

        schedule_url = self.api_path + "schedule/"
        params = {}
        if date:
            params['date'] = date
        response = self.get_response(schedule_url, params)
        return response
1363101
def run(self):
        """"""
        document = self.state.document
        env = document.settings.env
        buildpath = env.app.outdir
        link = self.arguments[0]

        try:
            r = requests.get(link)
            r.raise_for_status()
            downloadpath = os.path.join(buildpath, '_downloads')
            if not os.path.isdir(downloadpath):
                os.makedirs(downloadpath)
            rstfile = os.path.join(downloadpath, os.path.basename(link))
            with open(rstfile, 'w') as f:
                f.write(r.text)
            rstfile = os.path.relpath(rstfile, os.path.dirname(env.doc2path
                                                               (env.docname)))
            self.arguments = [rstfile]
            return super(RemoteInclude, self).run()
        except Exception:
            err = 'Unable to resolve ' + link
            return [document.reporter.warning(str(err), line=self.lineno)]
16719
def manage_schedule(self, tag, data):
        '''
        
        '''
        func = data.get('func', None)
        name = data.get('name', None)
        schedule = data.get('schedule', None)
        where = data.get('where', None)
        persist = data.get('persist', None)

        funcs = {'delete': ('delete_job', (name, persist)),
                 'add': ('add_job', (schedule, persist)),
                 'modify': ('modify_job',
                            (name, schedule, persist)),
                 'enable': ('enable_schedule', ()),
                 'disable': ('disable_schedule', ()),
                 'enable_job': ('enable_job', (name, persist)),
                 'disable_job': ('disable_job', (name, persist)),
                 'postpone_job': ('postpone_job', (name, data)),
                 'skip_job': ('skip_job', (name, data)),
                 'reload': ('reload', (schedule,)),
                 'list': ('list', (where,)),
                 'save_schedule': ('save_schedule', ()),
                 'get_next_fire_time': ('get_next_fire_time',
                                        (name,))}

        # Call the appropriate schedule function
        try:
            alias, params = funcs.get(func)
            getattr(self.schedule, alias)(*params)
        except TypeError:
            log.error('Function "%s" is unavailable in salt.utils.scheduler',
                      func)
1337315
def gen_report(report, sdir='./', report_name='report.html'):
    

    # Create report directory
    if not os.path.exists(sdir):
        os.makedirs(sdir)

    # Add a slash to file directory if not included to avoid DirNameFleName
    # instead of DirName/FileName being creaated
    if sdir[-1] != '/':
        sdir += '/'

    report_html = '<html><body>'

    if 'method' in report.keys():

        report_html += "<h1>Method: " + report['method'] + "</h1><p>"

        for i in report[report['method']]:

            if i == 'taper_window':

                fig, ax = plt.subplots(1)
                ax.plot(report[report['method']]['taper_window'],
                        report[report['method']]['taper'])
                ax.set_xlabel('Window (time). 0 in middle of window.')
                ax.set_title(
                    'Taper from ' + report[report['method']]['distribution'] + ' distribution (PDF).')
                fig.savefig(sdir + 'taper.png')

                report_html += "<img src='./taper.png' width=500>" + "<p>"

            else:

                report_html += "- <b>" + i + "</b>: " + \
                    str(report[report['method']][i]) + "<br>"

    if 'postprocess' in report.keys():

        report_html += "<p><h2>Postprocessing:</h2><p>"

        report_html += "<b>Pipeline: </b>"

        for i in report['postprocess']:

            report_html += " " + i + ","

        for i in report['postprocess']:

            report_html += "<p><h3>" + i + "</h3><p>"

            for j in report[i]:

                if j == 'lambda':

                    report_html += "- <b>" + j + "</b>: " + "<br>"

                    lambda_val = np.array(report['boxcox']['lambda'])
                    fig, ax = plt.subplots(1)
                    ax.hist(lambda_val[:, -1])
                    ax.set_xlabel('lambda')
                    ax.set_ylabel('frequency')
                    ax.set_title('Histogram of lambda parameter')
                    fig.savefig(sdir + 'boxcox_lambda.png')

                    report_html += "<img src='./boxcox_lambda.png' width=500>" + "<p>"
                    report_html += "Data located in " + sdir + "boxcox_lambda.csv <p>"

                    np.savetxt(sdir + "boxcox_lambda.csv",
                               lambda_val, delimiter=",")

                else:

                    report_html += "- <b>" + j + "</b>: " + \
                        str(report[i][j]) + "<br>"

    report_html += '</body></html>'

    with open(sdir + report_name, 'w') as file:
        file.write(report_html)
    file.close()
1323246
def make_report(storage_directory, old_pins, new_pins, do_update=False,
                version_mappings=None):
    """"""
    report = ""
    version_mappings = version_mappings or {}
    for new_pin in new_pins:
        repo_name, repo_url, commit_sha = new_pin
        commit_sha = version_mappings.get(repo_name, {}
                                          ).get(commit_sha, commit_sha)

        # Prepare our repo directory and clone the repo if needed. Only pull
        # if the user requests it.
        repo_dir = "{0}/{1}".format(storage_directory, repo_name)
        update_repo(repo_dir, repo_url, do_update)

        # Get the old SHA from the previous pins. If this pin didn't exist
        # in the previous OSA revision, skip it. This could happen with newly-
        # added projects and roles.
        try:
            commit_sha_old = next(x[2] for x in old_pins if x[0] == repo_name)
        except Exception:
            continue
        else:
            commit_sha_old = version_mappings.get(repo_name, {}
                                                  ).get(commit_sha_old,
                                                        commit_sha_old)

        # Loop through the commits and render our template.
        validate_commits(repo_dir, [commit_sha_old, commit_sha])
        commits = get_commits(repo_dir, commit_sha_old, commit_sha)
        template_vars = {
            'repo': repo_name,
            'commits': commits,
            'commit_base_url': get_commit_url(repo_url),
            'old_sha': commit_sha_old,
            'new_sha': commit_sha
        }
        rst = render_template('offline-repo-changes.j2', template_vars)
        report += rst

    return report
298443
def generate_schedule(today=None):
    """"""
    # We create a list of slots and schedule items
    schedule_days = {}
    seen_items = {}
    for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'):
        day = slot.get_day()
        if today and day != today:
            # Restrict ourselves to only today
            continue
        schedule_day = schedule_days.get(day)
        if schedule_day is None:
            schedule_day = schedule_days[day] = ScheduleDay(day)
        row = make_schedule_row(schedule_day, slot, seen_items)
        schedule_day.rows.append(row)
    return sorted(schedule_days.values(), key=lambda x: x.day.date)
125740
def _do_download(version, download_base, to_dir, download_delay):
    """"""
    py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
    tp = 'setuptools-{version}-{py_desig}.egg'
    egg = os.path.join(to_dir, tp.format(**locals()))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
            to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        _unload_pkg_resources()

    import setuptools
    setuptools.bootstrap_install_from = egg
474171
def schedule_window(report_type, start_at, stop_at, resolution):
    
    model_cls = get_scheduler_model(report_type)
    dbsession = db.create_scoped_session()
    schedules = dbsession.query(model_cls).filter(model_cls.active.is_(True))

    for schedule in schedules:
        args = (
            report_type,
            schedule.id,
        )

        # Schedule the job for the specified time window
        for eta in next_schedules(schedule.crontab,
                                  start_at,
                                  stop_at,
                                  resolution=resolution):
            schedule_email_report.apply_async(args, eta=eta)
562557
def get_file_object(username, password, utc_start=None, utc_stop=None):
    """"""

    if not utc_start:
        utc_start = datetime.now()

    if not utc_stop:
        utc_stop = utc_start + timedelta(days=1)

    logging.info("Downloading schedules for username [%s] in range [%s] to "
                 "[%s]." % (username, utc_start, utc_stop))

    replacements = {'start_time': utc_start.strftime('%Y-%m-%dT%H:%M:%SZ'), 
                    'stop_time':  utc_stop.strftime('%Y-%m-%dT%H:%M:%SZ')}
    
    soap_message_xml = (soap_message_xml_template % replacements)

    authinfo = urllib2.HTTPDigestAuthHandler()
    authinfo.add_password(realm, url, username, password)

    try:
        request = urllib2.Request(url, soap_message_xml, request_headers)
        response = urllib2.build_opener(authinfo).open(request)

        if response.headers['Content-Encoding'] == 'gzip':
            response = GzipStream(response)
    except:
        logging.exception("Could not acquire connection to Schedules Direct.")
        raise

    return response
1119100
def cli(obj):
    """"""
    client = obj['client']
    status = client.mgmt_status()

    now = datetime.fromtimestamp(int(status['time']) / 1000.0)
    uptime = datetime(1, 1, 1) + timedelta(seconds=int(status['uptime']) / 1000.0)

    click.echo('{} up {} days {:02d}:{:02d}'.format(
        now.strftime('%H:%M'),
        uptime.day - 1, uptime.hour, uptime.minute
    ))
584882
def download(date_array, tag, sat_id, data_path, user=None, password=None):
    

    import sys
    import os
    import pysftp
    import davitpy
    
    if user is None:
        user = os.environ['DBREADUSER']
    if password is None:
        password = os.environ['DBREADPASS']
        
    with pysftp.Connection(
            os.environ['VTDB'], 
            username=user,
            password=password) as sftp:
            
        for date in date_array:
            myDir = '/data/'+date.strftime("%Y")+'/grdex/'+tag+'/'
            fname = date.strftime("%Y%m%d")+'.' + tag + '.grdex'
            local_fname = fname+'.bz2'
            saved_fname = os.path.join(data_path,local_fname) 
            full_fname = os.path.join(data_path,fname) 
            try:
                print('Downloading file for '+date.strftime('%D'))
                sys.stdout.flush()
                sftp.get(myDir+local_fname, saved_fname)
                os.system('bunzip2 -c '+saved_fname+' > '+ full_fname)
                os.system('rm ' + saved_fname)
            except IOError:
                print('File not available for '+date.strftime('%D'))

    return
116846
def get
         schedule do
            inc_io
            @@log.info("Requesting: #{@url}")
            http = EM::HttpRequest.new(@url).get :redirects => 5
      
            http.callback do |h|
              succeed http.response
              dec_io
            end
    
            http.headers do |headers|
              unless OK_ERROR_CODES.include?(headers.status)
                fail("Error (#{headers.status}) with url:#{@url}")
                dec_io
              end
            end        
    
            http.errback do
              fail("Error downloading #{@url}")
              dec_io
            end       
          end
        self # Fluent interface
      end
165216
function scheduleSearch( country, date, callback ) {
    var url = apiBaseUrl+endpoints['schedule'].replace('$1', country).replace('$2', date);

    fetch(url, function(result) {
        callback(result);
    });
}
136849
def get(self, flex_sched_rule_id):
        """"""
        path = '/'.join(['flexschedulerule', flex_sched_rule_id])
        return self.rachio.get(path)
1358229
def download(args)
      if args.length != 1
        puts "missing report id for 'download' subcommand"
        return false
      end

      report_id = args[0].to_i
      report    = @common_args.account.reports.find { |r| r.id == report_id }
      if report.nil?
        puts "report '#{report_id}' not found"
        return false
      end

      if report.status != 'Completed'
        puts "cannot download report with status '#{report.status}'"
        return false
      end

      path_name = "test_report.xml"
      puts "Download report #{report.id} in #{path_name}"
      report.download(path_name)
      true
    end